Symbolic group names (as in Python) in Ruby Regular Expression

Went through this handy regex utility in Python (I'm new to Python). e.g. Using regex

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

I can refer to consistent data as

 m.group('id') 

(Full documentation: find the "symbolic group name" here )

In Ruby, we can access the mapped links with $1, $2 or with the MatchData object ( m[1], m[2] , etc.). Is there anything similar to Python character group names in Ruby?

+7
python ruby regex
source share
2 answers

There were no named groups in versions of Older Ruby (tx Alan to indicate this in a comment!), But if you are using Ruby 1.9 ...:

(?<name>subexp) expresses the named group in Ruby expressions; \k<name> is how you return a link to a named group in a substitution if that is what you are looking for!

+11
source share

Ruby 1.9 introduced named captures:

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

You can use \k<prefix> etc. for backlinks.

+10
source share

All Articles