How to use split from regex in python and keep your split word?
Question: Is there a way to use split function without losing the word or char, that you
using to split with?

for example:

    
    
    import re
    x = '''\
    1.
    abcde.
    2.
    fgh 2.5 ijk.
    3.
    lmnop
        '''
    print(x)
    
    listByNum = re.split(r'\d\.\D', x)
    
    print(listByNum) 
    

[![the
output](http://i.stack.imgur.com/5es14.png)](http://i.stack.imgur.com/5es14.png)
I want to keep the digit in the list

An other example:

    
    
    import re
    x = '''\
    I love stackoverflow. I love food.\nblah blah blah.
        '''
    print(x)
    
    listBySentences = re.split(r'\.', x)
    
    print(listBySentences)
    

[![output for example
2](http://i.stack.imgur.com/jgjnJ.png)](http://i.stack.imgur.com/jgjnJ.png)


Answer: Not very well documented, but you can use parentheses around the expression in
question:

    
    
    import re
    x = '''\
    1.
    abcde.
    2.
    fgh 2.5 ijk.
    3.
    lmnop
        '''
    print(x)
    
    listByNum = re.split(r'(\d\.\D)', x)
    
    print(listByNum) 
    # ['', '1.\n', 'abcde.\n', '2.\n', 'fgh 2.5 ijk.\n', '3.\n', 'lmnop\n    ']
    

* * *

To even _clean_ your data afterwards, you can use a list comprehension, like
so:

    
    
    listByNum = [num.strip() for num in re.split(r'(\d\.\D)', x) if num]
    # ['1.', 'abcde.', '2.', 'fgh 2.5 ijk.', '3.', 'lmnop']
    

* * *

To keep the digits within the splitted elements, you can use the newer
[**regex**](https://pypi.python.org/pypi/regex) module which supports
splitting on empty strings:

    
    
    import regex as re
    x = same string as above
    listByNum = [num.strip() for num in re.split(r'(?V1)(?=\d\.\D)', x) if num]
    # ['1.\nabcde.', '2.\nfgh 2.5 ijk.', '3.\nlmnop']
    

