How do I extract text that lies between parenthese

2018-12-31 19:55发布

I have a string User name (sales) and I want to extract the text between the brackets, how would I do this?

I suspect sub-string but I can't work out how to read until the closing bracket, the length of text will vary.

标签: c# .net regex
16条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 20:16
string input = "User name (sales)";

string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
查看更多
临风纵饮
3楼-- · 2018-12-31 20:17
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
查看更多
梦寄多情
4楼-- · 2018-12-31 20:17

The regex method is superior I think, but if you wanted to use the humble 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);

or

string input = "my name is (Jayne C)";
string output  = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);
查看更多
倾城一夜雪
5楼-- · 2018-12-31 20:18

Regular expressions might be the best tool here. If you are not famililar with them, I recommend you install Expresso - a great little regex tool.

Something like:

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;
}
查看更多
冷夜・残月
6楼-- · 2018-12-31 20:18
int start = input.IndexOf("(") + 1;
int length = input.IndexOf(")") - start;
output = input.Substring(start, length);
查看更多
笑指拈花
7楼-- · 2018-12-31 20:20

Here is a general purpose readable function that avoids using regex:

// 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);
}

To call it in your particular example you can do:

string result = ExtractBetween("User name (sales)", "(", ")");
查看更多
登录 后发表回答