tags:

views:

221

answers:

2

Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp

(?P<id>[a-zA-Z_]\w*)

I can refer to the matched data as

m.group('id')

(Full documentation: look for "symbolic group name" here)

In Ruby, we can access the matched references using $1, $2 or using the MatchData object (m[1], m[2] etc.). Is there something similar to Python's Symbolic Group Names in Ruby?

+4  A: 

Older Ruby releases didn't have named groups (tx Alan for pointing this out in a comment!), but, if you're using Ruby 1.9...:

(?<name>subexp) expresses a named group in Ruby expressions too; \k<name> is the way you back-reference a named group in substitution, if that's what you're looking for!

Alex Martelli
Be aware that named groups are a feature of the new Oniguruma regex engine. It replaced Ruby's old, underpowered regex engine quite recently, in Ruby 1.9, so there's a lot of reference material out there that hasn't caught up with the change.
Alan Moore
@Alan, thanks -- editing the A to point this out.
Alex Martelli
There's an Oniguruma gem for 1.8, though you'll need to install Oniguruma first to be able to use it - http://oniguruma.rubyforge.org/index.xhtml
kejadlen
Thanks - I searched a but more. Ruby 1.8 can be compiled with the Oniguruma library (and Ruby 1.9 can optionally be compiled with the older Ruby 1.8 regex implementation).http://angryruby.blogspot.com/2007/05/oniguruma-and-named-regexes-in-ruby-18.htmlAnd Regular Expressions Cookbook (http://oreilly.com/catalog/9780596520694) talks about this.
arnab
+2  A: 

Ruby 1.9 introduced named captures:

m = /(?<prefix>[A-Z]+)(?<hyphen>-?)(?<digits>\d+)/.match("THX1138.")
m.names # => ["prefix", "hyphen", "digits"]
m.captures # => ["THX", "", "1138"]
m[:prefix] # => "THX"

You can use \k<prefix>, etc, for back-references.

Marc-André Lafortune
Yes - with the Oniguruma engine.
arnab