views:

157

answers:

5

How can i get the string within a parenthesis with a custom function?

e.x. the string "GREECE (+30)" should return "+30" only

+2  A: 

For the general problem, I'd suggest using Regex. However, if you are sure about the format of the input string (only one set of parens, open paren before close paren), this would work:

int startIndex = s.IndexOf('(') + 1;
string result = s.Substring(startIndex, s.LastIndexOf(')') - startIndex);
Mehrdad Afshari
A: 

You could look a regular expressions, or otherwise play with the IndexOf() function

Rowland Shaw
+3  A: 

There are some different ways.

Plain string methods:

Dim left As Integer = str.IndexOf('(')
Dim right As Integer= str.IndexOf(')')
Dim content As String = str.Substring(left + 1, right - left - 1)

Regular expression:

Dim content As String = Regex.Match(str, "\((.+?)\)").Groups[1].Value
Guffa
+1  A: 

With regular expressions.

Dim result as String = System.Text.RegularExpressions.Regex.Match("GREECE (+30)", "\((?<Result>[^\)]*)\)").Groups["Result"].Value;

Code is not tested, but I expect only compilation issues.

Mike Chaliy
A: 

In Python, using the string index method and slicing:

>>> s = "GREECE(+30)"
>>> s[s.index('(')+1:s.index(')')]
'+30'
Anon