Search code examples
pythonregexpython-re

How to match an optional word between two other words?


Let's say I want to match words "green apple". I also want to match words like "green big apple".

How to write regular expression for this?

I wrote r"green [a-z+] apple", but this doesn't work.


Solution

  • You were close, but your + is inside the [] instead of outside, and also the word may not exist so you need to wrap the entire thing (and one of the spaces) in a ?, to match one word or no word (can replace with * for any number of middle words).

    import re
    
    pattern =  r"green ([a-z]+ )?apple"
    print(re.match(pattern, "green apple").group(0))
    print(re.match(pattern, "green big apple").group(0))
    

    Output:

    green apple
    green big apple