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.
views:
7051answers:
9
+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
2008-12-18 16:42:13
Expresso is ace!
DeletedAccount
2008-12-18 16:57:29
+10
A:
A very simple way to do it is by using regular expressions:
Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value
Diadistis
2008-12-18 16:42:24
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
2010-03-26 03:14:16
+5
A:
string input = "User name (sales)";
string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
Nick Allen - Tungle139
2008-12-18 16:43:30
You should of course only calculate the location of the first bracket once.
Martin Brown
2008-12-18 19:29:12
+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
2008-12-18 16:44:13
A:
Use a Regular Expression:
string test = "(test)";
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);
Will Dean
2008-12-18 16:47:39
+1
A:
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
Mr. Brownstone
2008-12-18 16:49:11
+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
2008-12-18 16:49:12
+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
2008-12-18 17:04:30