简体   繁体   中英

Ruby gsub! with Regex keep word

I want to turn a string line "variable.to_s" into "str(variable)" using gsub! with regex. I currently have

string = "variable.to_s"
string.gsub!(/\w+\.to_s/,/str(\w)/)

which obviously does not work as you cannot use regex in the second part of gsub, but how do I keep the \\w found in the gsub part but replacing the .to_s part?

You're capturing the wrong thing:

string.gsub!(/(\w+)\.to_s/, 'str(\1)')

gsub and gsub! take a string or regular expression as the first argument and a string or block as the second argument. You're sending a regular expression to both.

If you need to use a portion of the match in the second part, capture it with brackets. You did this inadvertently in your code but on the wrong side.

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