Starting with:
pattern = /(a)(.*?)(z)/ # => /(a)(.*?)(z)/
str = "my \\\\ string" # => "my \\\\ string"
Instead of doing:
"agggz".gsub(pattern, '\1' + str + '\3') # => "amy \\ stringz"
I'd do it like this:
"agggz"[pattern] # => "agggz"
$1 + str + $3 # => "amy \\\\ stringz"
Most of the time we really want to match a string to extract stuff out, and occasionally we want to munge a string to convert it into something else. In this case you want to extract stuff, so do that; Take the retrieved values and make what you really want by concatenation.
But there's a lot that doesn't make sense about the question and examples. If you know the string starts with a
, and ends with z
, then don't bother with a regex or gsub
(or sub
) at all:
'a' + str + 'z' # => "amy \\\\ stringz"
If you don't know what the first and last letters are, then why do you search for (a)
or (z)
? Your pattern should use wildcards: /^(.).*?(.)$/
:
pattern = /^(.).*(.)$/
"agggz"[pattern]
$1 + str + $2 # => "amy \\\\ stringz"
But, why even use a pattern or a method like sub
or gsub
?
target = "agggz"
target[0] + str + target[-1] # => "amy \\\\ stringz"