我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
我有一个字符串用户名(销售),我想提取括号之间的文本,我该如何做到这一点?
我怀疑子字符串,但我不知道如何阅读,直到右括号,文本的长度会有所不同。
当前回答
我在寻找一个非常相似的实现的解决方案时遇到了这个问题。
下面是我的实际代码片段。从第一个字符(索引0)开始子字符串。
string separator = "\n"; //line terminator
string output;
string input= "HowAreYou?\nLets go there!";
output = input.Substring(0, input.IndexOf(separator));
其他回答
也许是正则表达式?我认为这行得通……
\(([a-z]+?)\)
我发现正则表达式非常有用,但很难写。所以,我做了一些研究,发现这个工具可以让写它们变得如此简单。
不要因为语法很难理解而回避它们。它们可以如此强大。
一个非常简单的方法是使用正则表达式:
Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value
作为对(非常有趣的)评论的回应,这里是同一个正则表达式的一些解释:
\( # Escaped parenthesis, means "starts with a '(' character"
( # Parentheses in a regex mean "put (capture) the stuff
# in between into the Groups array"
[^)] # Any character that is not a ')' character
* # Zero or more occurrences of the aforementioned "non ')' char"
) # Close the capturing group
\) # "Ends with a ')' character"
使用正则表达式:
string test = "(test)";
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);
我认为regex方法更好,但如果你想使用卑微的子字符串
string input= "my name is (Jayne C)";
int start = input.IndexOf("(");
int stop = input.IndexOf(")");
string output = input.Substring(start+1, stop - start - 1);
or
string input = "my name is (Jayne C)";
string output = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);