简体   繁体   中英

How to assign named groups in a regex to local variables

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM