如何提取括号(圆括号)之间的文本?

我有一个stringUser name (sales) ,我想提取括号内的文字,我将如何做到这一点?

我怀疑子string,但我不能工作如何阅读,直到右括号,文本的长度会有所不同。

一个非常简单的方法是使用正则expression式:

 Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value 

作为(非常有趣)评论的回应,这里是相同的正则expression式和一些解释:

 \( # 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" 

如果你想远离正则expression式,我能想到的最简单的方法是:

 string input = "User name (sales)"; string output = input.Split('(', ')')[1]; 

假设你只有一对括号。

 string s = "User name (sales)"; int start = s.IndexOf("(") + 1; int end = s.IndexOf(")", start); string result = s.Substring(start, end - start); 

使用这个function:

 public string GetSubstringByString(string a, string b, string c) { return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length)); } 

这里是用法:

 GetSubstringByString("(", ")", "User name (sales)") 

和输出将是:

 sales 
 string input = "User name (sales)"; string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1); 

一个正则expression式可能? 我认为这会工作…

 \(([az]+?)\) 

正则expression式可能是这里最好的工具。 如果你不是他们的家庭,我build议你安装Expresso – 一个伟大的小正则expression工具。

就像是:

  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; } 
 using System; using System.Text.RegularExpressions; private IEnumerable<string> GetSubStrings(string input, string start, string end) { Regex r = new Regex(Regex.Escape(start) +`"(.*?)"` + Regex.Escape(end)); MatchCollection matches = r.Matches(input); foreach (Match match in matches) yield return match.Groups[1].Value; } 

使用正则expression式:

 string test = "(test)"; string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value; Console.WriteLine(word); 
 input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1); 

regex方法是我认为,但如果你想使用谦逊的substring

 string input= "my name is (Jayne C)"; int start = input.IndexOf("("); int stop = input.IndexOf(")"); string output = input.Substring(start+1, stop - start - 1); 

要么

 string input = "my name is (Jayne C)"; string output = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1); 

这是一个避免使用正则expression式的通用可读函数:

 // Returns the text between 'start' and 'end'. string ExtractBetween(string text, string start, string end) { int iStart = text.IndexOf(start); iStart = (iStart == -1) ? 0 : iStart + start.Length; int iEnd = text.LastIndexOf(end); if(iEnd == -1) { iEnd = text.Length; } int len = iEnd - iStart; return text.Substring(iStart, len); } 

要在您的特定示例中调用它,您可以这样做:

 string result = ExtractBetween("User name (sales)", "(", ")"); 

当我正在寻找一个类似的实现的解决scheme时,我遇到了这个问题。

这是我的实际代码片段。 从第一个字符(索引0)开始子string。

  string separator = "\n"; //line terminator string output; string input= "HowAreYou?\nLets go there!"; output = input.Substring(0, input.IndexOf(separator)); 

我发现正则expression式非常有用,但写起来却很困难。 所以,我做了一些研究,发现这个工具 ,使它们很容易写。

不要回避他们,因为语法很难弄清楚。 他们可以如此强大。

这个代码比这里的大多数解决scheme(如果不是全部的话)更快,以string 扩展方法打包,不支持recursion嵌套:

 public static string GetNestedString(this string str, char start, char end) { int s = -1; int i = -1; while (++i < str.Length) if (str[i] == start) { s = i; break; } int e = -1; while(++i < str.Length) if (str[i] == end) { e = i; break; } if (e > s) return str.Substring(s + 1, e - s - 1); return null; } 

这一个更长,更慢,但它更好地处理recursion嵌套:

 public static string GetNestedString(this string str, char start, char end) { int s = -1; int i = -1; while (++i < str.Length) if (str[i] == start) { s = i; break; } int e = -1; int depth = 0; while (++i < str.Length) if (str[i] == end) { e = i; if (depth == 0) break; else --depth; } else if (str[i] == start) ++depth; if (e > s) return str.Substring(s + 1, e - s - 1); return null; } 
 int start = input.IndexOf("(") + 1; int length = input.IndexOf(")") - start; output = input.Substring(start, length); 

这是类似于上面的一些答案,但不使用正则expression式,是一个简单的复制和粘贴方法为你:

 public String getSubstring(String startChar, String endChar, String initString) { return initString.substring((initString.indexOf(startChar) + 1), (initString.indexOf(endChar))); }