简体   繁体   中英

Using Regex Global Variable with Ruby gsub

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.

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"

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