开发者

Use Ruby RegEx to identify phrase in sentence

开发者 https://www.devze.com 2023-03-19 17:13 出处:网络
I want to write a condition that evaluates to tru开发者_开发百科e if a string contains the phrase: \"no row at position 0\".

I want to write a condition that evaluates to tru开发者_开发百科e if a string contains the phrase: "no row at position 0".

For example, let's assume the string is:

"Feed returned error status: There is no row at position 0."


You don't need a regular expression to look for a fixed substring, just include? will do:

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


For this specific case, you don't need a regex. A simple index will do:

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 will return nil if it didn't find the string:

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

精彩评论

暂无评论...
验证码 换一张
取 消