Chris
Chris

Reputation: 2290

Using named capture groups inside Ruby gsub blocks (regex)

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)

Upvotes: 32

Views: 8794

Answers (1)

oldergod
oldergod

Reputation: 15000

You are looking for

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

Upvotes: 47

Related Questions