r"\."+".+"+"apple"+".+"+"\."
This line is a bit odd; why compress so many single lines? You could just use r '.. + apple. +. '.
In any case, the problem with your regular expression is its greed. By default, x+ will match x as often as possible. This way your .+ Will match as many characters as possible (any characters); including dots and apple s.
What you want to use instead is a non-greedy expression; can you usually do this by adding ? at the end:. .+? .
This will force you to get the following result:
['.I like to eat apple. Me too.']
As you can see, you no longer get both apple offers, but still Me too. . This is due to the fact that you are still consistent . after apple , which also makes it impossible to capture the next sentence.
The working regular expression will be: r'\.[^.]*?apple[^.]*?\.'
Here you do not look at any characters, but only at those characters that are not points. We also allow not matching any characters at all (because after apple there are no inaccurate characters in the first sentence). Using this expression leads to the following:
['.I like to eat apple.', ". Let go buy some apples."]
poke
source share