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