代码之家  ›  专栏  ›  技术社区  ›  user2969402

以行首显示python re.search行为

  •  0
  • user2969402  · 技术社区  · 7 年前

    我有一个简单的字符串测试,如下所示:

    test = 'Liquid marinade for cooking fish liquid vegetables'
    

    我想使用正则表达式匹配字符串中的关键字“liquid marinade”。(我匹配其他关键字,需要使用单词边界,因此 string.index() 不足以)

    我编译以下regex:

    regex = re.compile(r'\b(liquid marinade)\b')
    

    然后执行不区分大小写的搜索:

    regex.search(test, re.IGNORECASE)
    

    什么也得不到。

    如果我尝试的话也一样 ^(liquid marinade)\b .

    使用 \b(marinade for)\b 匹配第二个和第三个单词,所以我猜问题是字符串以单词开头 Liquid 但这不应该包括在 \b 作为词的边界?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jean-François Fabre    7 年前

    那就行了

    regex = re.compile(r'\b(liquid marinade)\b', re.IGNORECASE)
    print(regex.search(test))
    

    这个 re.IGNORECASE 传递给的参数 search 实际上是起始位置。

    被抓了很多次 re.sub 以及(经典问题: Python re.sub with a flag does not replace all occurrences ,我建议在添加标志时使用 flags 关键字,而不是 位置传球 因为在 re 方法(开始位置、计数、命名):

    flags=re.IGNORECASE
    

    如果它起作用(比如 再保险公司 re.compile ,然后,好的,如果不支持它,您将得到(如这里所示):

    regex.search(test,flags=re.IGNORECASE)  # wrong but explicit!
    TypeError: 'flags' is an invalid keyword argument for this function
    

    至少它不做其他的事…