Search code examples
pythonsplitpython-re

combining split with findall


I'm splitting a string with some separator, but want the separator matches as well:

import re

s = "oren;moish30.4.200/-/v6.99.5/barbi"
print(re.split("\d+\.\d+\.\d+", s))
print(re.findall("\d+\.\d+\.\d+", s))

I can't find an easy way to combine the 2 lists I get:

['oren;moish', '/-/v', '/barbi']
['30.4.200', '6.99.5']

Into the desired output:

['oren;moish', '30.4.200', '/-/v', '6.99.5', '/barbi']

Solution

  • From the re.split docs:

    If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

    So just wrap your regex in a capturing group:

    print(re.split(r"(\d+\.\d+\.\d+)", s))