Regex gsub

i have already working these phone.gsub(regex, “<
#{regex.match(phone)} >” ) but i think is another way to do it not?
like phone.gsub(regex,"< \1 >")
but the last instrucction does not bring the regex.match

what i want to do , is suppose you have the string “i love my dad "
the regex find dad then substitute dad , i have already solved
but i want
to know if the a fancy way to do the gsub like gsub(regex,”< \1 >")
instead of phone.gsub(regex, “< #{regex.match(phone)} >” )

Try

“i love my dad”.gsub(/dad/) { |match| “<#{match}>” }

or,

“i love my dad”.gsub(/dad/) { “<#{$&}>” }

On Sat, Feb 26, 2011 at 5:33 PM, Lorenzo Brito M.
[email protected] wrote:

str = “i love my dad”
str2 = “I went to Baghdad”

p str.gsub(/(dad)/,‘<\1>’) #> “i love my ”

p str2.gsub(/(dad)/,‘<\1>’) #> “I went to Bagh”

Do you also want that second match?

Harry

Lorenzo Brito M. wrote in post #984075:

i have already working these phone.gsub(regex, “<
#{regex.match(phone)} >” ) but i think is another way to do it not?
like phone.gsub(regex,"< \1 >")
but the last instrucction does not bring the regex.match

It’s to do with how double-quoted strings interpret backslashes.

irb(main):001:0> “< \1 >”
=> “< \001 >”
irb(main):002:0> ‘< \1 >’
=> “< \1 >”
irb(main):003:0> “< \1 >”
=> “< \1 >”
irb(main):004:0> “< \1 >”.size
=> 6
irb(main):005:0> puts “< \1 >”
< \1 >
=> nil

Note that “< \1 >” contains a single backslash - a backslash escaped
with a backslash :slight_smile:

But you’d probably be better using the block form of gsub anyway:

phone.gsub(regex) { “< #{$&} >” }