【问题标题】:Strings pulled from Regex apear to match but dont从正则表达式中提取的字符串似乎匹配但不匹配
【发布时间】:2013-01-11 00:26:27
【问题描述】:

这对我来说没有任何意义。我试图断言这两个日期是相同的。它们看起来一样,但不知何故它们是不同的。

#assert correct time and date
assert_equal(/[0-9]{1,2}, [0-9]{4} at [0-9]{1,2}:[0-9]{2} [A-Z]{2}/.match($driver.find_element(:class, "flash-information").text), /[0-9]{1,2}, [0-9]{4} at [0-9]{1,2}:[0-9]{2} [A-Z]{2}/.match($driver.find_element(:class, "news_date").text))

这是我得到的失败。

F
===============================================================================
Failure: <#<MatchData "10, 2013 at 4:13 PM">> expected but was
<#<MatchData "10, 2013 at 4:13 PM">>. 

   39:     #assert correct time and date
=> 40:     assert_equal(/[0-9]{1,2}, [0-9]{4} at [0-9]{1,2}:[0-9]{2} [A-Z]{2}/.match($driver.find_element(:class, "flash-information").text), /[0-9]{1,2}, [0-9]{4} at [0-9]{1,2}:[0-9]{2} [A-Z]{2}/.match($driver.find_element(:class, "news_date").text))

我在测试单元中运行它

【问题讨论】:

  • 请在标题上更具体一些(例如,我们应该知道标题到底是什么问题)

标签: ruby regex selenium testunit


【解决方案1】:

您不是在匹配字符串,而是在匹配 MatchData 对象。

a = "foobar".match /f/   # #<MatchData "f">
b = "foobar".match /f/   # #<MatchData "f">
c = "barfoo".match /f/   # #<MatchData "f">

a == b   # true
a == c   # false

如果你想比较匹配的字符串,那么你必须从MatchData对象中提取它们:

a[0]           # "f"
a[0] == b[0]   # true
a[0] == c[0]   # true

【讨论】:

  • 谢谢,所以它是在比较对象的确切实例?
  • 没有。它比较匹配的字符串、匹配的组、开始和结束位置以及使用的正则表达式。在我的示例中,开始和结束位置不匹配,所以它是false。要亲自查看,请转到ruby-doc.org/core-1.9.3/MatchData.html#method-i-3D-3D,将光标悬停在mtch == mtch2 行上,然后将显示“单击切换源”。点击它来切换源,你可以自己检查它到底做了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2014-10-08
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多