Вопрос

This is the code:

pattern = /(a)(.*?)(z)/
 => /(a)(.*?)(z)/ 

# Correct
str = "my // string"
 => "my // string" 
"agggz".gsub(pattern, '\1' + str + '\3')
 => "amy // stringz" 

# Wrong - there is one missing slash
str = "my \\\\ string"
 => "my \\\\ string" 
"agggz".gsub(pattern, '\1' + str + '\3')
 => "amy \\ stringz" 

When I have a pattern described in a string, I could use Regexp.escape to make sure that the pattern will work as I expected.

What I'm looking for is something similar, but for the second parameter of gsub, that is, independently of the str, when used as the value to be replaced in the gsub, it will copy correctly the value to the position.

How can I do that?

Это было полезно?

Решение

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"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top