Created
June 22, 2012 21:47
-
-
Save avit/2975403 to your computer and use it in GitHub Desktop.
Ruby Regexp match named capture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Regex with two named captures both named "word" | |
r = %r{ | |
(?<word>[a-z]+)\s+ | |
(?<word>[a-z]+) | |
}xi | |
m = r.match("one two") | |
# => #<MatchData "one two" word:"one" word:"two"> | |
m.captures | |
# => ["one", "two"] | |
m[:word] | |
# => "two" | |
# | |
# Where is [:word] "one"? | |
# | |
# It's visible in the MatchData captures. | |
# Shouldn't [:word] be enumerable if there is more than one? | |
# | |
# | |
# Further, the \g<name> construct should reuse previous groups: | |
# http://www.ruby-doc.org/core-1.9.3/Regexp.html#label-Subexpression+Calls | |
# | |
# My understanding is that this should be the same as above, but this time it drops "one" altogether: | |
# | |
r = %r{ | |
(?<word>[a-z]+)\s+ | |
\g<word> | |
}xi | |
m = r.match("one two") | |
# => #<MatchData "one two" word:"two"> | |
m.captures | |
# => ["two"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment