A good way to insert a string before a regular expression in Ruby

What a good way to do this? It looks like I could use a combination of several different methods to achieve what I want, but there is probably a simpler method that I skip. For example, the PHP function preg_replace will do this. Anything like that in Ruby?

simple example of what I plan to do:

orig_string = "all dogs go to heaven" string_to_insert = "nice " regex = /dogs/ end_result = "all nice dogs go to heaven" 
+6
source share
2 answers

This can be done using Ruby "gsub", according to:

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') 
+10
source
 result = subject.gsub(/(?=\bdogs\b)/, 'nice ') 

The regular expression checks each position in the string to see if the whole word dogs can be found there, and then the nice string is inserted there.

The \b anchor \b ensure that we do not accidentally match hotdogs , etc.

+3
source

Source: https://habr.com/ru/post/893045/


All Articles