Learning Ruby

Simple Substitution with Capture

If you use parentheses in your regular expression to capture portions of the string, these are available to you as \1, \2, etc. Where \1 is the first capture group and \2 the second, etc.


"Superman and Batman".sub(/(\w+) and (\w+)/, '\2 and \1') 
# => Batman and Superman
You will need to escape the backslash if your replacement string is specified in double quotes.

"Superman and Batman".sub(/(\w+) and (\w+)/, "\\2 and \\1") 
# => Batman and Superman

 

 

January 05, 2010 at 2:57 am