Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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"
like image 561
Axl Avatar asked Jul 19 '11 06:07

Axl


1 Answers

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')
like image 74
Ash Eldritch Avatar answered Nov 15 '22 07:11

Ash Eldritch