简体   繁体   中英

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)

You are looking for

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM