Ruby regex- does gsub store what it matches? -
if use
.gsub(/matchthisregex/,"replace_with_this")
does gsub store matches regex somewhere? i'd use matches in replacement string. example like
"replace_with_" + matchedregexstring + "this"
in above example matchedregexstring stored match gsub? sorry if confusing, don't know how else word that.
from fine manual:
if replacement
string
substituted matched text. may contain back-references pattern’s capture groups of form\d
, d group number, or\k<n>
, n group name. if double-quoted string, both back-references must preceded additional backslash. however, within replacement special match variables, such&$
, not refer current match.
[...]
in block form, current match string passed in parameter, , variables such$1
,$2
, $`,$&
, ,$'
set appropriately. value returned block substituted match on each call.
if don't care capture groups (i.e. things (expr)
in regex) can use block form , $&
:
>> 'where pancakes house?'.gsub(/is/) { "-#{$&}-" } => "where -is- pancakes house?"
if have capture groups can use \n
in replacement string:
>> 'where pancakes house?'.gsub(/(is)/, '-\1-') => "where -is- pancakes house?"
or $n
in block:
>> 'where pancakes house?'.gsub(/(is)/) { "-#{$1}-" } => "where -is- pancakes house?"
Comments
Post a Comment