0

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

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

1
  • 2
    I'd say regular expressions are capable of doing this. Commented Jul 4, 2009 at 17:40

5 Answers 5

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

Comments

0

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

Comments

0

In Python, using the string index method and slicing:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.