【问题标题】:Python re.search behavior with beginning of linePython re.search 行为与行首
【发布时间】:2018-07-03 20:54:25
【问题描述】:

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

test = 'Liquid marinade for cooking fish liquid vegetables'

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

我编译了以下正则表达式:

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

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

regex.search(test, re.IGNORECASE)

什么也得不到。

如果我尝试使用^(liquid marinade)\b,也是如此。

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

【问题讨论】:

  • regexObj.search 的第二个参数是您开始搜索的位置。

标签: python regex


【解决方案1】:

有效

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

您传递给searchre.IGNORECASE 参数实际上是开始位置。

re.sub 中也被多次捕获(经典问题:Python re.sub with a flag does not replace all occurrences),我建议您在添加标志时使用flags 关键字,而不是位置传递 因为re 方法中可能还有其他选项(开始位置,计数,你命名):

flags=re.IGNORECASE

如果它有效(如在re.subre.compile 中),那么好吧,如果它不受支持,你会得到(如这里):

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

至少它没有做其他事情......

【讨论】:

    猜你喜欢
    • 2013-09-02
    • 2015-03-30
    • 2015-01-30
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多