【问题标题】:Regex check if specific multiple words present in a sentence正则表达式检查句子中是否存在特定的多个单词
【发布时间】:2018-08-19 01:22:28
【问题描述】:

是否有一个正则表达式供我们检查字符串中是否存在多个单词

例如:

sentence = "hello i am from New York city"

我想检查句子中是否存在“hello”、“from”和“city”。

我尝试过使用

re.compile("hello|from|city")

但没有运气,因为即使找到一个匹配项,它也会返回 true。

【问题讨论】:

  • 我不知道 python,但你可以尝试类似 (?=hello)(?=from)(?=city) 在 perl 中工作的东西
  • @mankowitz 这行不通,因为如果一个位置紧跟在hello 之后,那么from 也不一定紧跟它。
  • 对不起:(?=.*hello)(?=.*from)(?=.*city)

标签: python regex python-2.7 pattern-matching


【解决方案1】:

您不能交替,因为任何交替的匹配都会满足正则表达式。相反,从字符串的开头使用多个前瞻:

sentence1 = "hello i am from New York city"
sentence2 = "hello i am from New York"
regex = re.compile(r"^(?=.*hello)(?=.*from)(?=.*city)")
print(regex.match(sentence1))
print(regex.match(sentence2))

输出:

<_sre.SRE_Match object; span=(0, 0), match=''>
None

【讨论】:

    【解决方案2】:

    您可以使用all() 内置方法。

    文档here

    该函数实际上将iterable 类型作为参数。

    例子:

    words = ["hello", "from", "city"]
    if all(word in 'hello from the city' for word in words):
      # Do Something
    

    【讨论】:

      【解决方案3】:

      您可以在不使用正则表达式的情况下执行此操作,只需检查sentence 中每个单词(来自words)的入口:

      sentence = "hello i am from New York city"
      words = ['hello', 'from', 'city']
      all([w in sentence.split() for w in words])
      

      在我看来,由于清晰,这种方式更可取。

      【讨论】:

        【解决方案4】:

        试试:

        >>> sentence = "hello i am from New York city"
        >>> def f(s):
            return all(s.split().__contains__(i) for i in ['hello','from','city'])
        
        >>> f(sentence)
        True
        

        【讨论】:

          猜你喜欢
          • 2012-07-10
          • 1970-01-01
          • 2020-02-19
          • 2022-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-18
          相关资源
          最近更新 更多