This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Named backreferences
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Normally you might have some code with a regex like this:
str = "hello world"
reg = /^(\w+?)\s(\w+)$/
first = $1
last = $2
Oh, sure, you might just use MatchData#captures instead of the globals. The point is you're referring to them by index, in one form or another. What if you could refer to them by name instead?
# pseudo.rb
str = "hello world"
reg = /^(?<first>\w+?)\s(?<last>\w+)$/
match = reg.match(str)
first = match[:first]
last = match[:last]
Python (though not Perl afaik, surprisingly) already has this ability in the form of the groupdict() method for its MatchData object:
>>> import re
>>> re.compile('a(?P<mid>.*)c').match('abc').groupdict()
{'mid': 'b'}
I've been playing with Oniguruma recently, trying to get symbolic group names to work. I was hoping that it would be something as simple as the pseudo.rb I pasted above. Unfortunately, that doesn't work. There's no MatchData#group method that returns a hash, either. In fact, I don't see how to refer back to it at all.
Anyway, assuming we do get a way to access named references, that will be pretty cool.