Tonight at the
Chicago Area Ruby Meetup (CHIRB), we had some lightning-round presentations, and without too much preparation I decided to release and demo some code I had written for dealing with Regular Expressions.
The library in essence allows you to use the totally under-utilized embedded-comment faculty in Ruby's Regular Expression Extensions to label your captures.
For those who don't know, a comment in a Ruby Regexp looks like
(?#this), so if you want to label a capture, you can embed comments in the parentheses for that capture, like this:
/((?#number)\d+)-((?#word)\w+)/.
Of course that doesn't buy you anything on its own, so I wrote a library called 'named_captures.rb' available in my public svn repository
here.
With this library, you can now use that Regexp above like so:
my_regexp = /((?#number)\d+)-((?#word)\w+)/
my_match = my_regexp.match("i got 128-bit encryption!")
my_match[:number] # <= '128'
my_match[:word] # <= 'bit'
Feel free to explore and send me email if you use this at
brendan@usergenic.com. Comments on this post welcome as well.
Labels: named_captures.rb, regexp, regular expressions