How to prevent \g subexpression from overwriting the grouped content in Ruby Regex

Viewed 42

eg.

> /(?<ip>(?:\d+\.){3}\d+)\s*(?<mask>\g<ip>)/ =~ "1  abc  192.168.200.111 255.255.255.0"
> $~
=> #<MatchData "192.168.200.111 255.255.255.0" ip:"255.255.255.0" mask:"255.255.255.0">

according to the result above, \g<ip> captures "255.255.255.0", but also store them to ip group.

How to get the content of the first ip group: 192.168.200.111.

1 Answers

Reverse the subexpression call (I just found out by experimenting, not sure if it is robust)

>> /(?<ip>\g<mask>)\s*(?<mask>(?:\d+\.){3}\d+)/ =~ "1  abc  192.168.200.111 255.255.255.0"
=> 8
>> ip
=> "192.168.200.111"
>> mask
=> "255.255.255.0"
Related