【问题标题】:Faulty Regex or strange behavior?错误的正则表达式或奇怪的行为?
【发布时间】:2020-10-16 07:37:07
【问题描述】:

您好,我在这里发布我的问题,因为我不明白我的潜在错误。我正在解析成分列表。其中一些有诸如“* no-ogm”之类的指控。我成功地在字典中提取了大部分这些指控,以便直接从其他成分列表中提取已经引用的指控。问题是我的正则表达式适用于所有在线正则表达式测试器,但在我的 jupyter 笔记本中没有,我不明白为什么。这是一个例子:

string='''chickpeas* (31%), water, sesame oil* (11%), tofu* (soybeans*, water, gelling agent (nigari (magnesium chloride))), onions*, carrots*, yeast*, celery*, non-hydrogenated sunflower oil*, cashew nuts*, tomato paste*, vegetable bouillon* (sea salt, maize starch*, glucose syrup*, sunflower oil*, carrots*, onion*, parsnips*, turmeric*, ginger*, parsley*, nutmeg*, lovage*, bay leaves*, black pepper*), sea salt, ginger*, locust bean*, coriander*, turmeric*, cumin*, fenugreek*, nutmeg, black pepper*, cinnamon*, mustard seeds*, cardamom*, cayenne pepper* *from organic agriculture'''

和正则表达式:

pattern=re.findall('\*{1,3}\s{0,2}\bfrom organic agriculture\b\s{0,2}$',string)

在 Regex101 和 Pythex 中,可以清楚地找到字符串“*来自有机农业”的子集。在我的 jupyter 笔记本模式中返回“无”......为什么?我尝试了许多正则表达式标志来纠正这种行为,但是......没有任何效果。

这个问题在大规模范围内尤其成问题,因为我有一个如上所述的指控字典,我循环遍历我的每个字典键以在多个字符串中找到相应的模式。

提前感谢您的帮助

【问题讨论】:

    标签: python regex parsing


    【解决方案1】:

    您应该在这里使用所谓的原始字符串,即代替:

    pattern=re.findall('\*{1,3}\s{0,2}\bfrom organic agriculture\b\s{0,2}$',string)
    

    pattern=re.findall(r'\*{1,3}\s{0,2}\bfrom organic agriculture\b\s{0,2}$',string)
    

    如果您使用正则表达式类字符,这一点至关重要,例如 \s

    【讨论】:

    • 实际上它现在正在工作,但我不明白为什么我在这里需要原始字符串字符。我需要更深入地了解 python 正则表达式文档......我不想不理解。非常感谢您的快速回答!
    • @TristanSalord:如果您想了解,请阅读re docs,从Regular expressions use the backslash开始...
    【解决方案2】:

    模式中b 之前的双反斜杠:'\*{1,3}\s{0,2}\\bfrom organic agriculture\\b\s{0,2}$'(其他此类字符为换行符、\'"aafn、@9876543131 @、tvx,后跟一个十六进制字符代码),或者在模式前加上r:r'\*{1,3}\s{0,2}\bfrom organic agriculture\b\s{0,2}$',这样反斜杠就不会被视为转义序列的开头(@987654321 @)。

    【讨论】:

    • 我从你的回答中了解到 re.search('*',string) 不会有问题,但是如果你想捕获'* %',例如,你需要像 re .search(r'*\s\%') 因为您正在处理一系列特定字符?
    • @Tristan Salord,Python 为字符串文字中以反斜杠开头的某些序列赋予了特殊含义,包括\b,它是退格字符(参见docs.python.org/2.0/ref/strings.html)。
    • 天哪!是这样吗????!!!非常感谢....该死的!
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多