使用Ruby RegEx来识别句子中的短语

时间:2011-07-13 05:53:20

标签: ruby regex

如果字符串包含短语:“no position at position 0”,我想编写一个求值为true的条件。

例如,我们假设字符串是:

“Feed返回错误状态:位置0处没有行。”

2 个答案:

答案 0 :(得分:4)

您不需要正则表达式来查找固定的子字符串,只需include?即可:

"Feed returned error status: There is no row at position 0.".include?("no row at position 0")
# => true

答案 1 :(得分:1)

对于这种特定情况,您不需要正则表达式。一个简单的index将会:

irb(main):001:0> a = "Feed returned error status: There is no row at position 0."
=> "Feed returned error status: There is no row at position 0."
irb(main):002:0> a.index("no row at position 0")
=> 37
如果找不到字符串,

index将返回nil

irb(main):003:0> a.index("no row at position 0a")
=> nil