1
votes

I am trying to assign named groups of my regex expression matches to local variables. For example, I am trying to capture a string for a date input and refer to the named group month and day as local variables:

input = "2015-01-24" 
expr = /\d{4}-(?<month>\d{2})-(?<day>\d{2})/ 
input =~ expr #=> 0

However, month or day are undefined variables after the match. How do I access month and day as local variables?

According to the Ruby doc, typing the group variable name would return the captured value ("dollars" in this example)

/\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ "$3.67" #=> 0 
dollars #=> "3"

I'd appreciate any recommended resources as well.

1

1 Answers

6
votes

Read more carefully the document that you cited:

When named capture groups are used with a literal regexp on the left-hand side of an expression and the =~ operator, the captured text is also assigned to local variables with corresponding names.

Your code:

input =~ expr

does not confirm to this in two respects: (1) expr is not a literal regexp but is a regex assigned to a variable, (2) you have the regex on the right hand side.

If you follow the document, then you can refer to the captures as local variables.