Select contents of parenthesis in substring (VB.NET)

483 views Asked by At

I have a substring of text like so:

Serial Port Name (COM 1)

How would I go about getting the contents of the above parenthesis?

Thank you in advance.

2

There are 2 answers

3
James Thorpe On BEST ANSWER

This is what regular expressions are ideal for, although this is a fairly basic match for them:

Dim str as String = "Serial Port Name (COM 1)"
Dim inbrackets as String = Regex.Match(str, "\((.*)\)").Groups(1).Value

This expression looks for parentheses - the \( and \) - with any number of characters in between - .* means match any character except new line zero or more times. The inner part is also wrapped in parentheses to make it a capturing group - ie (.*). This means that the .Groups property can be used to retrieve the individual text from that capturing group. The first group (ie .Groups(0).Value) would be the whole match, and would give you "(COM 1)".

0
Bradley Uffner On

You could use String.IndexOf to find the index of each paren, then use String.Substring to pull out the parts you want.

You could also use Regex with an appropriate pattern to locate a match.