简体   繁体   中英

A good way to insert a string before a regex match in Ruby

What's a good way to do this? Seems like I could use a combination of a few different methods to achieve what I want, but there's probably a simpler method I'm overlooking. For example, the PHP function preg_replace will do this. Anything similar in Ruby?

simple example of what I'm planning to do:

orig_string = "all dogs go to heaven"
string_to_insert = "nice "
regex = /dogs/

end_result = "all nice dogs go to heaven"

It can be done using Ruby's "gsub", as per:

http://railsforphp.com/2008/01/17/regular-expressions-in-ruby/#preg_replace

orig_string = "all dogs go to heaven"
end_result = orig_string.gsub(/dogs/, 'nice \0')
result = subject.gsub(/(?=\bdogs\b)/, 'nice ')

The regex checks for each position in the string whether the entire word dogs can be matched there, and then it inserts the string nice there.

The word boundary anchors \b ensure that we don't accidentally match hotdogs etc.

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