我有两个字符串.其中一个参数是花括号中的唯一名称.可以有任意数量的参数,任何名称.
例如,使用以下字符串:
字符串1:
This string is called Fred and Johnson and is very interesting
Run Code Online (Sandbox Code Playgroud)
字符串2:
This string is called {name} and is {rating} interesting
Run Code Online (Sandbox Code Playgroud)
我想保存:
parameters = {"name" => "Fred and Johnson", "rating" => "very"}
Run Code Online (Sandbox Code Playgroud)
有关如何实现这一目标的任何帮助?
line1 = "This file is called Fred and Johnson and is very interesting"
line2 = "This file is called {name} and is {rating} interesting"
def match_lines(line1, line2)
line2_re_code = Regexp.escape(line2).gsub(/\\{(.+?)\\}/, '(?<\1>.+?)')
line2_re = Regexp.new("^#{line2_re_code}$")
if match = line2_re.match(line1)
hash = Hash[match.names.map { |name| [name, match[name]] }]
puts hash.inspect
else
puts "No match"
end
end
match_lines(line1, line2)
# => { "name" => "Fred and Johnson", "rating" => "very" }
match_lines(line1, "foo")
# => No match
match_lines("foo", line2)
# => No match
Run Code Online (Sandbox Code Playgroud)
编辑:添加锚点.另外,解释:
我们将从模式行创建一个正则表达式,首先转义特殊的正则表达式字符,这样就可以了:
'This\ file\ is\ called\ \{name\}\ and\ is\ \{rating\}\ interesting'
Run Code Online (Sandbox Code Playgroud)
然后我们将占位符转换为Oniguruma命名捕获:
'This\ file\ is\ called\ (?<name>.+?)\ and\ is\ (?<rating>.+?)\ interesting'
Run Code Online (Sandbox Code Playgroud)
然后添加锚点并从中创建一个正则表达式,以确保line1前面没有东西或者最后没有东西:
/^This\ file\ is\ called\ (?<name>.+?)\ and\ is\ (?<rating>.+?)\ interesting$/
Run Code Online (Sandbox Code Playgroud)
EDIT2:如果匹配失败Regexp#match将返回nil,或者是MatchData对象; 您可以使用它MatchData#[]来访问各个占位符值.您可以使用MatchData#names以查看哪些占位符存在.
EDIT3:哎呀...正如评论中所说,names应该是match.names.