【问题标题】:How to tell if a string contains a substring如何判断字符串是否包含子字符串
【发布时间】:2020-08-26 03:55:41
【问题描述】:

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

字符串示例:

"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”开头的完整句子。

【问题讨论】:

  • 你可以使用r = /\bthe +\w+ +is in the kitchen\b/。然后"the cat is in the kitchen".match?(r) #=> true"the dog is in the kitchenette".match?(r) #=> false
  • 您的问题没有明确提出。 ... 是什么意思?必须出现“猫”或“狗”的位置?为什么include? 不够?它会告诉您子字符串是否出现,仅此而已。为什么开头需要“the”?您是否尝试使用正则表达式?

标签: ruby string


【解决方案1】:
def the_in_the_kitchen(string)
    return string.match?(/the \w+ is in the kitchen/i)
end

这应该可行。我使用了一个正则表达式,并将单词catdog 替换为\w+,这意味着一系列字母。我还在正则表达式中添加了 i 标志,它代表 ignore case。因此 The DOG is In The KITchen 也可以。

【讨论】:

  • 请注意在我对问题的评论中需要分词。
  • @CarySwoveland 我不同意,作者没有指定分词的必要性。但是,如果确实如此,评论可能会很有用:)
  • 好的,那么让我们“给小厨房里的狗穿衣服”吧。我们说的是英语的使用。 :-)
猜你喜欢
  • 1970-01-01
  • 2012-08-29
  • 2017-10-15
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 2014-07-28
  • 1970-01-01
相关资源
最近更新 更多