-1

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.

Rachael
  • 1,965
  • 4
  • 29
  • 55

2 Answers2

1

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)".

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Wow. This is awesome, and I think you just once and for all sold me on finally tackling regex. Great explanation. Thank you! – Rachael Jun 16 '15 at 16:29
  • 1
    @Rachael If you do start off down that road, it's useful to have good tools. My current favourite for regexs is http://regex101.com. For example, [here is this one](https://regex101.com/r/yM3lE7/1). – James Thorpe Jun 16 '15 at 16:30
  • Thank you so much, that reference really helps (It's always been overwhelming trying to find a good reference). – Rachael Jun 16 '15 at 19:55
0

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.

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76