比较不包括参数的字符串

Sco*_*tty 0 ruby string

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

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

例如,使用以下字符串:

字符串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)

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

Ama*_*dan 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
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.

  • 非常有趣,但我不确定问题是否明确.例如,如果`line1 ="这个文件被称为Fred并且是非常有趣的"`,那么`match_lines(line1,line2)#=>名称:Fred,评级:Johnson并且非常`. (2认同)