如何判断一个字符串是否包含一个子字符串

时间:2020-05-10 16:56:49

标签: ruby string

我想知道一个字符串是否包含一个子字符串。

字符串示例:

"Hey boy, the cat is in the kitchen ?"
"I want to know if the dog is in the kitchen"

子字符串:

"the ... is in the kitchen"

但是我需要忽略“猫,狗”一词,我该怎么做?

string.include?是不正确的方法,因为我希望在开头加上“ the”的完整句子。

1 个答案:

答案 0 :(得分:0)

def the_in_the_kitchen(string)
    return string.match?(/the \w+ is in the kitchen/i)
end

这应该有效。我使用了一个正则表达式,并用cat替换了dog\w+一词,这意味着一系列字母。我还向正则表达式添加了i标志,它代表 i gnore的情况。因此,厨房里的狗狗也可以工作。