简体   繁体   English

python regex跳过可选单词不起作用

[英]python regex skipping optional words not working

I have been trying to find matches where they may be optional words in the string that need to be ignored if they are present. 我一直在尝试寻找匹配项,这些匹配项可能是字符串中的可选单词,如果存在,则需要忽略。

The code I tried is: 我试过的代码是:

    import re
    str = '''
         topping consensus estimates 
         topping analysis' consensus estimate
         topping estimate
    '''
    for m in re.finditer(r'(?P<p3c>topping\s+(?:\w+\s(?!estimate)){0,2}(estimate))',str):
        print(m.group())
    print('done')

I want to get all three cases found in the string but only get the last. 我想在字符串中找到所有三种情况,但只能得到最后一种。 I want to skip up to two words between topping and estimate but cannot guarantee that they will be analysis and consensus. 我想在填充和估计之间跳过两个词,但不能保证它们将是分析和共识。 I tried with (?:\\w+\\s(?!estimate)){0,2} to skip up to two word to get the results but it is not working for some reason. 我尝试使用(?:\\w+\\s(?!estimate)){0,2}跳过最多两个单词来获取结果,但是由于某种原因它不起作用。

You don't need to get "topping estimate" as the result. 您不需要得到“最高估计”。 What you really want is to check whether each line starts with topping followed by 2 or fewer words, then estimate or estimates . 真正想要的是检查每行是否以打topping开头,后接2个或更少的单词,然后estimateestimates

This regex will help you: 此正则表达式将帮助您:

^topping(\s\S+){0,2}\sestimates?\s*$

Match this against each line, or multiple lines if you turn on m . 将其与每行或多行(如果启用m匹配。 It will tell you whether the string satisfies the requirement. 它会告诉您字符串是否满足要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM