views:

7051

answers:

9

I have a string "User name (sales)" and I want to extract the text between the brackets, how would I do this? I suspect substring but I can't work out how to read until the closing bracket, the length of text will vary.

+9  A: 

A regex maybe? I think this would work...

\(([a-z]+?)\)
chills42
+4  A: 

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;
  }
Jennifer
Expresso is ace!
DeletedAccount
+10  A: 

A very simple way to do it is by using regular expressions:

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value
Diadistis
I love it when people say "a simple way is to use regular expressions" and then offer what amounts to a string of indecipherable hieroglyphics (it's especially fun when different people suggest regex and each comes up with a different set of hieroglyphics for the same problem). :)
Deltics
+5  A: 
string input = "User name (sales)";

string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
Nick Allen - Tungle139
You should of course only calculate the location of the first bracket once.
Martin Brown
+5  A: 

Assuming that you only have one pair of parenthesis.

string s = "User name (sales)";
int start = s.IndexOf("(");
int end = s.IndexOf(")")
string result = s.substring(start, end - start -1)
Ross Goddard
A: 

Use a Regular Expression:

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

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);
DrG
int stop = s.IndexOF(")", start) is appropriate.
Jimmy
yes sure, good point :D
DrG
+1  A: 

The regex method is not superior if performance is a consideration. Regex is using a sledgehammer on a flea.

As you described it, your bracket problem is extremely limited and well-defined. I like the answer by Tungle139 above.

Regex is better for problems with a lot less uniformity/predictability in them.

abelenky