比较不包括参数的字符串

时间:2015-12-03 03:38:19

标签: ruby string

我有两个字符串。其中一个参数是花括号中的唯一名称。可以有任意数量的参数,任何名称。

  1. 我想知道它们是否匹配,不包括参数化部分。参数化部分可以是多个单词和任何长度。
  2. 我想将参数化部分保存到哈希中,键是参数的名称,不包括花括号。
  3. 例如,使用以下字符串:

    字符串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"}
    

    有关如何实现这一目标的任何帮助?

1 个答案:

答案 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将返回nilMatchData对象;您可以使用MatchData#[]访问各个占位符值。您可以使用MatchData#names查看哪些占位符存在。

EDIT3:哎呀...正如评论中所说,names应该是match.names