hypehuman
hypehuman

Reputation: 1369

C# Regex "+" group returning empty string

I'm trying to match the following strings and extract the numbers:

"Control 1"
"Control 2"

and I want to make sure that I avoid similar strings such as:

"Indication 1"
"Local Control Input 2"

This is the pattern I'm using:

@"^Control (?<slot>\d+)$"

It works perfectly, and match.Groups["slot"].Value returns the number. However, I discovered that I also need to be able to match the following:

"Office In 1"
"Office In 2"

I modified my regex to this:

@"^(?:Control)|(?:Office In) (?<slot>\d+)$"

The problem is that now, match.Groups["slot"].Value is returning an empty string! Doesn't the + require that there be at least one digit? I randomly tried adding an extra non-capturing group around the two existing ones:

@"^(?:(?:Control)|(?:Office In)) (?<slot>\d+)$"

That fixes the problem, but I'm not sure why.

Upvotes: 1

Views: 1393

Answers (1)

FrankieTheKneeMan
FrankieTheKneeMan

Reputation: 6800

Alternation has the highest precedence in Regular expressions. Your original regex is "^(?:Control)" (Control at the beginning of the string) OR "(?:Office In) (?<slot>\d+)$" (Office In #### at the end of the string).

Try this regular expression:

@"^(?:Control|Office In) (?<slot>\d+)$"

Upvotes: 4

Related Questions