dotNET
dotNET

Reputation: 35450

Non-capturing group not working in Regex

Using regex, I want to match the following strings:

January 25
Jan 25

I'm capturing month and date parts separately but want to return only the first 3 characters of month name if there's full month name, so I'm using non-capturing group (?:) for the characters "uary":

(?<M>(Jan(?:uary)?)) (?<D>\d\d)

Unfortunately, the group M always returns full month name; i.e. it captures the non-capturing group too.

I have already turned on ExplicitCapture flag. I've used both RegExBuilder and Rad Software's Regular Expression Designer to make sure it is not because of the tool.

Upvotes: 2

Views: 1025

Answers (2)

Mark Byers
Mark Byers

Reputation: 839114

Your capturing group should surround only Jan.

(?<M>Jan)(?:uary)? (?<D>\d{1,2})

Your original expression is roughly equivalent to (?<M>January|Jan) (?<D>\d\d). The non-capturing group does not mean that the match is removed from existing capturing groups. It means only that no new capturing group is created.

Upvotes: 4

xdazz
xdazz

Reputation: 160943

Try:

(?<M>Jan)(?:uary)? (?<D>\d\d)

Upvotes: 1

Related Questions