OrElse
OrElse

Reputation: 9959

String substring function

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

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

Upvotes: 0

Views: 1713

Answers (5)

Anon
Anon

Reputation: 12498

In Python, using the string index method and slicing:

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

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

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

Upvotes: 3

Mike Chaliy
Mike Chaliy

Reputation: 26658

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.

Upvotes: 1

Guffa
Guffa

Reputation: 700232

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

Upvotes: 5

Rowland Shaw
Rowland Shaw

Reputation: 38130

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

Upvotes: 0

Related Questions