我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
当前回答
非常类似于@Gustavo Baiocchi Costa,但偏移量是用另一个中间子字符串计算的。
int innerTextStart = input.IndexOf("(") + 1;
int innerTextLength = input.Substring(start).IndexOf(")");
string output = input.Substring(innerTextStart, innerTextLength);
其他回答
非常类似于@Gustavo Baiocchi Costa,但偏移量是用另一个中间子字符串计算的。
int innerTextStart = input.IndexOf("(") + 1;
int innerTextLength = input.Substring(start).IndexOf(")");
string output = input.Substring(innerTextStart, innerTextLength);
string input = "User name (sales)";
string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
正则表达式可能是这里最好的工具。如果你不熟悉它们,我建议你安装Expresso -一个很棒的小正则表达式工具。
喜欢的东西:
Regex regex = new Regex("\\((?<TextInsideBrackets>\\w+)\\)");
string incomingValue = "Username (sales)";
string insideBrackets = null;
Match match = regex.Match(incomingValue);
if(match.Success)
{
insideBrackets = match.Groups["TextInsideBrackets"].Value;
}
假设你只有一对括号。
string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
也许是正则表达式?我认为这行得通……
\(([a-z]+?)\)