【问题标题】:Match a substring that might contain reserved characters匹配可能包含保留字符的子字符串
【发布时间】:2016-11-21 20:19:21
【问题描述】:

如果我正在测试的字符串包含正则表达式字符,我在将一个字符串与另一个字符串匹配时遇到了一些问题。

背景:我正在编写一个脚本,将新闻文章从 2 个旧系统迁移到一个。在某些情况下,这些故事在系统中是重复的,所以我正在运行一个脚本来检查存档文件(以 html 形式)中存储的数据,以查看当前故事的标题是否与存档中的任何内容匹配。

#...(for each line) 
line.match(title) then
    return true
end

这通常有效,除非我在标题中有正则表达式字符,例如:

<span class="title">$8.9 Million Grant for UC Center Focused on Occupational Safety and Health</span>

不匹配

$8.9 Million Grant for UC Center Focused on Occupational Safety and Health

这是 irb 的一些示例输出来演示

2.3.0 :012 > str = '<span class="title">$8.9 Million Grant for UC Center Focused on Occupational Safety and Health</span>'
2.3.0 :020 > str.match("$8.9 Million Grant for UC Center Focused on Occupational Safety and Health")
 => nil 
2.3.0 :021 > str.match("\\$8.9 Million Grant for UC Center Focused on Occupational Safety and Health")
 => #<MatchData "$8.9 Million Grant for UC Center Focused on Occupational Safety and Health"> 
2.3.0 :022 > str.match("8.9 Million Grant for UC Center Focused on Occupational Safety and Health")
 => #<MatchData "8.9 Million Grant for UC Center Focused on Occupational Safety and Health"> 
2.3.0 :023 > 

所以我很确定 $ 是问题所在,问题源于它是一个递归正则表达式字符。

Ruby 不是我的日常语言,我很难确定在哪里查看是否有 ruby​​ 方法可以在不依赖正则表达式的情况下进行匹配,或者按字面意思处理模式,或者自动转义潜在的正则表达式特殊字符。感谢您的帮助。

【问题讨论】:

  • 您在 15 分钟后接受了提供的第一个答案??
  • 成功了,而且很简洁。
  • 在选择答案之前等待一段时间(例如,至少几个小时)有几个原因。首先,早期选择可能会阻碍其他答案。在这种情况下,如果@philomony 没有提供答案(并且没有其他人给出该答案)怎么办?其次,它使那些仍在准备答案的人短路。第三,选择的答案有时是错误的,您不想阻止成员检查它。此外,我知道没有理由这么快选择答案。

标签: ruby regex


【解决方案1】:

如果您不需要 MatchData(例如目标文本在字符串中出现的位置),更简单的解决方案是使用 String#include?

str.include?("$8.9 Million")
# => true

如果您确实需要匹配发生的位置,使用String#index 更简单:

str.index("$8.9 Million")
# => 20

【讨论】:

  • 一旦我确定了目标,就会提出同样的建议。
【解决方案2】:
str.match(Regexp.new(Regexp.escape("$8.9 Million ...")))
=> #<MatchData "$8.9 Million Grant for UC Center Focused...

【讨论】:

  • 谢谢。就是这样。
猜你喜欢
  • 1970-01-01
  • 2017-04-16
  • 2015-07-27
  • 2019-04-24
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 2016-10-18
  • 2012-03-24
相关资源
最近更新 更多