regex - Why does capturing named groups in Ruby result in "undefined local variable or method" errors? -
i having trouble named captures in regular expressions in ruby 2.0. have string variable , interpolated regular expression:
str = "hello world" re = /\w+/ /(?<greeting>#{re})/ =~ str greeting
it raises following exception:
prova.rb:4:in
<main>': undefined local variable or method
greeting' main:object (nameerror)
shell returned 1
however, interpolated expression works without named captures. example:
/(#{re})/ =~ str $1 # => "hello"
named captures must use literals
you encountering limitations of ruby's regular expression library. regexp#=~ method limits named captures follows:
- the assignment not occur if regexp not literal.
- a regexp interpolation,
#{}
, disables assignment. - the assignment not occur if regexp placed on right hand side.
you'll need decide whether want named captures or interpolation in regular expressions. cannot have both.
Comments
Post a Comment