Skip to content

Instantly share code, notes, and snippets.

@avit
Created June 22, 2012 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avit/2975403 to your computer and use it in GitHub Desktop.
Save avit/2975403 to your computer and use it in GitHub Desktop.
Ruby Regexp match named capture
# 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