Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbolic Group Names (like in Python) in Ruby Regular Expression

Tags:

python

regex

ruby

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?

like image 737
arnab Avatar asked Jan 19 '10 01:01

arnab


2 Answers

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!

like image 156
Alex Martelli Avatar answered Nov 15 '22 20:11

Alex Martelli


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.

like image 37
Marc-André Lafortune Avatar answered Nov 15 '22 21:11

Marc-André Lafortune