Split string, include separator, multiple matches

Viewed 30

My string is s = "ABC foo bar 123 ABC baz nice 345". and the separator is ABC, so:

>>> s = "ABC foo bar 123 ABC baz nice 345
>>> output = re.findall(r"(ABC.*)", s)
>>> output
[ABC foo bar 123 ABC baz nice 345]

I want [ABC foo bar 123, ABC baz nice 345].

What am I doing wrong?

1 Answers

You may use this regex with a positive lookahead:

>>> import re
>>> s = "ABC foo bar 123 ABC baz nice 345"
>>> print(re.findall(r'\bABC .*?(?=\sABC\s|$)', s))
['ABC foo bar 123', 'ABC baz nice 345']

RegEx Details:

  • \bABC : Match word ABC followed by a space
  • .*?: Match 0 or more any characters (lazy match)
  • (?=\sABC\s|$): Positive Lookahead to assert that we have space + ABC + space ahead of the current position or there is an end of line
Related