Ruby regex- does gsub store what it matches?

Tommy picture Tommy · Apr 5, 2013 · Viewed 17.2k times · Source

If i use

.gsub(/matchthisregex/,"replace_with_this")

does gsub store what it matches with the regex somewhere? I'd like to use what it matches in my replacement string. For example something like

"replace_with_" + matchedregexstring + "this"

in my above example where the matchedregexstring would be the stored match from gsub? Sorry if that was confusing, I don't know how else to word that.

Answer

mu is too short picture mu is too short · Apr 5, 2013

From the fine manual:

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d, where d is a group number, or \k<n>, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.
[...]
In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

If you don't care about capture groups (i.e. things like (expr) in the regex) then you can use the block form and $&:

>> 'where is pancakes house?'.gsub(/is/) { "-#{$&}-" }
=> "where -is- pancakes house?"

If you do have capture groups then you can use \n in the replacement string:

>> 'where is pancakes house?'.gsub(/(is)/, '-\1-')
=> "where -is- pancakes house?"

or $n in the block:

>> 'where is pancakes house?'.gsub(/(is)/) { "-#{$1}-" }
=> "where -is- pancakes house?"