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.
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.
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
This should work fine .
/(green)(.+)(apple)/
The answer to your question is not simple because you need to decide how you want to handle different scenarios. For example:
Below is an example of what the pattern will capture.
green apple
green big apple
banana green small blueberry apple orange strawberry