user3290526
user3290526

Reputation: 139

Ruby regular expression groups

I am trying to match strings that might represent ranges somewhere in a document but can't quite figure out one thing about the groups... I have this so far:

/(^-?[0-9]+)(\.\.+)(-?[0-9]+$)/

Which matches 1..10, -20...20, -01234567890...-999999999, etc. However, I want the second group ($2) to have a value ONLY if the middle was 3 digits instead of two. So I would want it to be like:

=~ -01234567890...-999999999
$1 = -01234567890
$2 = ...
$3 = -999999999

=~ 1..10
$1 = 1
$2 = (empty because only two dots instead of 3)
$3 = 10

Any way to specify this, to only make a group if it's a certain value?

Upvotes: 1

Views: 43

Answers (1)

acarlon
acarlon

Reputation: 17274

You can use:

(^-?[0-9]+)(?:(?:[.]{,2})|([.]{,3}))(-?[0-9]+$)

which will only put the result in the second group if it is three ..

Explanation:

  • ?: - non-capturing group.
  • | - OR

Note that (?:[.]{,2}) is non-capturing while ([.]{,3}) will capture the group.

Upvotes: 1

Related Questions