I have the string "I like lettuce and carrots and onions"
in Python.
I thought I could get the following matches ["I like lettuce", "I like lettuce and carrots", "I like lettuce and carrots and onions"]
by using a regex like .* and
. (The regex should match any character up to " and".)
However, using the greedy version (.* and
) gives me only the last match, and using the non-greedy version (.*? and
) gives me only the first match.
How can I get all three matches?
(I do not need a regex solution.)
You can use simple splitting and construct strings without an expensive
regex
:If you need result in a list, go for a list-comprehension:
I wouldn't use an re at all: What is wrong with:
which gives you a list from which you construct the desired strings.
For fun, use the string
partition
method in Python 3. It searches a string for a substring, and returns a 3-tuple. When there's a match, it'sOnce you're used to it, it's very pleasant - no indexing needed, and it makes it easy to get the right results. So while this code is longer than some other ways, you should be able to reason about it easily:
which prints