Paramesh
Paramesh

Reputation: 371

How to do 'or' matching but not capture the 'or' part in a regex?

I am looking for a regex which can match both the date strings. I am having trouble with specifying the 'or' expression: /\d{4}-\d{2}-(XX|\d{2})/ doesn't work as it returns only the XX part:

"2007-01-XX 2008-01-01".scan(/\d{4}-\d{2}-XX/)
["2007-01-XX"]

"2007-01-XX 2008-01-01".scan(/\d{4}-\d{2}-\d{2}/)
["2008-01-01"]

Upvotes: 4

Views: 105

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

"2007-01-XX 2008-01-01".scan(/(\d{4}-\d{2}-(XX|\d{2}))/).map(&:first)

Upvotes: 0

ruakh
ruakh

Reputation: 183456

Use a non-capturing group of the form (?:...) instead of a capturing group of the form (...). So:

"2007-01-XX 2008-01-01".scan(/\d{4}-\d{2}-(?:XX|\d{2})/)

Upvotes: 7

Related Questions