我有一个字符串User name (sales)
,我想在括号之间提取文本,我该怎么做?
我怀疑子字符串,但我无法弄清楚如何阅读,直到结束括号,文本的长度会有所不同.
一个非常简单的方法是使用正则表达式:
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 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);
使用此功能:
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
正则表达式可能是这里最好的工具.如果你不熟悉它们,我建议你安装Expresso - 一个很棒的小正则表达式工具.
就像是:
Regex regex = new Regex("\\((?\\w+)\\)"); string incomingValue = "Username (sales)"; string insideBrackets = null; Match match = regex.Match(incomingValue); if(match.Success) { insideBrackets = match.Groups["TextInsideBrackets"].Value; }
string input = "User name (sales)"; string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
一个正则表达式可能吗?我认为这会奏效......
\(([a-z]+?)\)
using System; using System.Text.RegularExpressions; private IEnumerableGetSubStrings(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; }