Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Regex Global Variable with Ruby gsub

Tags:

regex

ruby

I'm trying to use the regex global variable with the ruby gsub! method.

What I have in mind is something like this:

MyTextString.gsub!(/regex expression/,$1)

This is how I've approached it but its not working. Is this possible or perhaps my regex isn't working.

like image 828
Mutuelinvestor Avatar asked Mar 26 '26 15:03

Mutuelinvestor


1 Answers

Use '\1' instead of $1 ($1 references a variable which doesn't exist yet, since you haven't matched the regex yet)

Also, "my regexp isn't working" makes it difficult to help. A better phrase would be one which explains why it isn't working (string is same afterwards, or an error is raised, or whatever), and provides the data (string and regex) necessary to reproduce the problem.

str = "abcdefg"
str.gsub!(/a(.)c/, '\1')
str # => "bdefg"
like image 83
Joshua Cheek Avatar answered Mar 29 '26 04:03

Joshua Cheek



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!