Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping "$" using gsub()

Tags:

regex

ruby

I'm trying to replace a preceding "$" in a string with "\$". For example, "$5 special" should become "\$5 special".

I've tried:

"$5 special".gsub(/^\$/, "\$") => "$5 special"  
"$5 special".gsub(/^\$/, "\\$") => "\\$5 special"  
"$5 special".gsub(/^\$/, "\\\$") => "\\$5 special"

Anyone know how to do this?

like image 585
trliner Avatar asked Aug 24 '26 00:08

trliner


2 Answers

Your second example,

"$5 special".gsub(/^\$/, "\\$")

Should do it. The reason why you see two slashes in your output, is due to Ruby escaping the slash in the string for printing it as a literal. If you print it to standard out, you'd see it's what you expect:

irb(main):009:0> a = "$5 special".gsub(/^\$/, "\\$")
=> "\\$5 special"
irb(main):011:0> print a
\$5 special=> nil
like image 115
yan Avatar answered Aug 25 '26 23:08

yan


Just use single quotes for the substitution:

>> "$5 special".gsub(/^\$/, '\$') #=> "\\$5 special"
>> puts "$5 special".gsub(/^\$/, '\$') #=> nil
\$5 special
like image 26
Michael Kohl Avatar answered Aug 25 '26 22:08

Michael Kohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!