DDulla
DDulla

Reputation: 679

Regex (.NET) - Unrecognized grouping construct

I'm stumped on the following getting the following regex to work (VB.NET)

Input:

 +1.41 DS +0.93 DC x 3* @12.5 mm (4.00 Rx Calc)

Expected Output:

 +0.93

I've gotten as far as the following expression:

 DS[ \t]*[+\-][ \t]*\d{1,2}\.\d{2}

This returns a result of

DS +0.93

I need to return only +0.93 (without any leading whitespace), when i modify the Regex as:

(?DS[ \t]*)([+\-][ \t]*\d{1,2}\.\d{2})

I get the error unrecognized grouping construct, I don't understand why it's giving me this error. I think my non-matching group is incorrect, but i can't find why/where?

Upvotes: 1

Views: 118

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627419

You may use a positive lookbehind here:

(?<=DS[ \t]*)[+-][\t ]*\d{1,2}\.\d{2}
 ^^^

See the regex demo

To make sure you match the number and DS as whole words (with no letters, digits or _ in front and at the back) use word boundaries:

(?<=\bDS[ \t]*)[+-][\t ]*\d{1,2}\.\d{2}\b

Or a negative lookahead (?!\d) after \d{2}:

(?<=\bDS[ \t]*)[+-][\t ]*\d{1,2}\.\d{2}(?!\d)

See another regex demo.

Details

  • (?<=\bDS[ \t]*) - a positive lookbehind that matches a location in string that is immediately preceded with DS as a whole word followed with 0+ spaces or tabs
  • [+-] - a + or -
  • [\t ]* - 0+ spaces or tabs
  • \d{1,2} - 1 or 2 digits
  • \. - a dot
  • \d{2} - 2 digits
  • (?!\d) - no digit allowed immediately to the right of the current location.

VB.NET demo:

Dim my_rx As Regex = New Regex("(?<=\bDS[ \t]*)[+-][\t ]*\d{1,2}\.\d{2}(?!\d)")
Dim my_result As Match = my_rx.Match(" +1.41 DS +0.93 DC x 3* @12.5 mm (4.00 Rx Calc)")
If my_result.Success Then
    Console.WriteLine(my_result.Value) ' => +0.93
End If

Upvotes: 1

Related Questions