2

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.

1
  • What is "not working"? Please be more specific. Commented Dec 22, 2017 at 6:29

1 Answer 1

4

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.

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. It will tell you whether the string satisfies the requirement.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I needed to modify your suggestion to fit my needs but you have the right approach. I am using just r'topping(\s\S+){0,2}\sestimate' since I do not know where they will be in the text.
@Pat If you think my answer answers your question, please consider accepting it by clicking on that checkmark!
@Pat Define "no longer works". What are you trying to match? What do you expect it to match? What actually matched?
@Pat Try using search instead of findall
I don't know what happened, but I restarted from scratch and compile is now working!!! Not sure what the problem was but it seems to be gone. Thanks again Sweeper for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.