Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using named capture groups inside Ruby gsub blocks (regex)

Tags:

regex

ruby

gsub

I'm trying to use a named capture group inside a block in Ruby. $1 still works, but I'd like to reference it using the name I gave.

"foo /(bar)".gsub(/(?<my_word> \(.*?\) )/x) do |match|   puts "$1 = #{$1} and $my_word = #{$my_word}" end 

Expected:$1 = (bar) and $my_word = (bar)

like image 412
Chris Avatar asked May 16 '13 04:05

Chris


1 Answers

You are looking for

"foo /(bar)".gsub(/(?<my_word> \(.*?\) )/x) do |match|   puts "$1 = #{$1} and $my_word = #{$~[:my_word]}" end 
like image 148
oldergod Avatar answered Sep 21 '22 05:09

oldergod