[英]Using regex to replace parameters in a string
I am trying to iterate through elements of a struct, look for strings that include the format {...}
, and replace them with a corresponding string from a hash. 我试图遍历结构的元素,查找包含格式
{...}
字符串,并用散列中的相应字符串替换它们。 This is the data I'm using: 这是我正在使用的数据:
Request = Struct.new(:method, :url, :user, :password)
request = Request.new
request.user = "{user} {name}"
request.password = "{password}"
parameters = {"user" => "first", "name" => "last", "password" => "secret"}
This is attempt 1: 这是尝试1:
request.each do |value|
value.gsub!(/{(.+?)}/, parameters["\1"])
end
In this attempt, parameters["\\1"] == nil
. 在此尝试中,
parameters["\\1"] == nil
。
Attempt 2: 尝试2:
request.each do |value|
value.scan(/{(.+?)}/) do |match|
value.gsub!(/{(.+?)}/, parameters[match[0]])
end
end
This results in request.user == "first first"
. 这导致
request.user == "first first"
。 Trying parameters[match]
results in nil
. 尝试
parameters[match]
结果nil
。
Can anyone assist solving this? 谁能协助解决这个问题?
Neither of your attempt will work because arguments of gsub!
你的尝试都不会起作用,因为
gsub!
论点gsub!
are evaluated prior to the call of gsub!
在
gsub!
调用之前进行评估gsub!
. 。
parameters[...]
will be evaluated prior to replacement, so it has no way to reflect the match. 在更换之前将评估
parameters[...]
,因此无法反映匹配。 In addition, "\\1"
will not be replaced by the first capture even if that string was the direct argument of gsub!
此外,即使该字符串是
gsub!
的直接参数, "\\1"
也不会被第一次捕获所取代gsub!
. 。 You need to escape the escape character like
"\\\\1
". 你需要转义像
"\\\\1
”这样的转义字符。 To make it work, you need to give a block to gsub!
为了使它工作,你需要给
gsub!
一个块gsub!
. 。
But instead of doing that, try to use what already is there. 但是,不要这样做,尝试使用已经存在的东西。 You should use string format
%{}
and use symbols for the hash. 您应该使用字符串格式
%{}
并使用符号作为哈希。
request.user = "%{user} %{name}"
request.password = "%{password}"
parameters = {user: "first", name: "last", password: "secret"}
request.each do |value|
value.replace(value % parameters)
end
You can use gsub
with a block. 你可以使用带有块的
gsub
。
request.each do |e|
e.gsub!(/{.+?}/) { |m| parameters[m[1...-1]] } if e
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.