Main Content

Search and replace in Ruby - Ruby Regular Expressions

Archive - Originally posted on "The Horse's Mouth" - 2010-01-31 07:00:25 - Graham Ellis

"If you want to replace one part of a string by another in Ruby, you can use the sub method on your string object. The first parameter you give to the method is the string you want to replace, and the second is the string you want to replace it by."

OK - that's the easy bit ... but what if ....

If you want to replace ALL occurrences of a string, you should use the gsub method rather than the sub method

If instead of replacing an exact string, you want to replace something that's a particular pattern you would find within a string, you replace the first parameter with a Ruby style regular expression - there's an example of these [here], including a long block of comments that takes you through each of the elements.

If you want to mention part of the incoming string in the string it is replaced by, you may do so by capturing the sections of interest in round brackets in the incoming regular expression, and referring to them as , , etc, in the output string

If you want to replace the last match rather than the first, you can't do so directly ... but you CAN start your regular expression with (.*) which will do a "gredy capture" and move whatever's in the rest of the regular expression as far to the right as possible and still match it. So:
  update = message.sub(/(.*)!/,' ;-) ')
will replace the LAST ! with a smiley face ;-)

Finally - you don't always have to use sub and / or gsub. When you do a match or use the =~ operator, the incoming string is matched and split down into three special global variables:
  $` - the bit before the match ("dollar backquote")
  $& - the bit that matched ("dollar ampersand")
  $' - the bit after the match ("dollar forward quote")
which you can then use to rebuild a new string from its elements.

There are examples of all of these on an demonstration from our Ruby Training Courses which I have published on our web site [here]. There is a further example too - showing regular expressions in Ruby for cleaning user input.