Named capture group in regular expression

I need help with a regex to write numbers and hyphens from the following line: "some text and stuff 200-1234EM are some other things"

It may also appear without a trim part: "some text 123EM another text"

I need either "200-1234" or "123" in the named capture group.

I tried this: \b([0-9]{0,3}\-{0,1}[0-9]{3})EM\b

It matches, but it is not a named group.

When I try to name the group as follows: I get \b(?<test>[0-9]{0,3}\-{0,1}[0-9]{3})EM\bthe error message "Unknown external group near index 34"

I need this to work in a .NET RegEx class

Thanks!

+1
source share
1 answer
resultString = Regex.Match(subjectString, @"\b(?<number>\d+(?:-\d+)?)EM\b").Groups["number"].Value;

. , .

:

    @"
\b            # Assert position at a word boundary
(?<number>    # Match the regular expression below and capture its match into backreference with name "number"
   \d            # Match a single digit 0..9
      +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   (?:           # Match the regular expression below
      -             # Match the character "-" literally
      \d            # Match a single digit 0..9
         +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   )?            # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
EM            # Match the characters "EM" literally
\b            # Assert position at a word boundary
"
+3

All Articles