How to split text based on numbers with dots in Python?

Viewed 575

I have following simple text:

2 of 5 deliveries some text some text... 1. 3 of 5 items some text some text... 2. 1 of 5 items found in box some text...

Now I want that on the basis of numbers [0.-9.] the text should be splitted as following: (each row represents on entry in a list).

2 of 5 deliveries some text some text...,
3 of 5 items some text some text...,
1 of 5 items found in box some text...

This is the desired output. However, it does not really work with regex with re.split('([0\.-9\.]+)', text). It always separates by numbers only. What would be the most clever way to convert this with Python?

2 Answers

You can use the following pattern:

>>> re.split(r'\s+\d+\.\s+', text)
['2 of 5 deliveries some text some text...',
 '3 of 5 items some text some text...',
 '1 of 5 items found in box some text...']

EXPLANATION:

>>> re.split(r'''
        \s+        # Matches leading spaces to the separator
        \d+        # Matches digit character
        \.         # Matches '.' character
        \s+        # Matches trailing spaces after the separator
        ''', text, flags=re.VERBOSE)

['2 of 5 deliveries some text some text...',
 '3 of 5 items some text some text...',
 '1 of 5 items found in box some text...']

try:

import re

text = '2 of 5 deliveries some text some text... 1. 3 of 5 items some text some text... 2. 1 of 5 items found in box some text...'

print(re.split('[0-9]\.', text))

Output:

['2 of 5 deliveries some text some text... ', ' 3 of 5 items some text some text... ', ' 1 of 5 items found in box some text...']
Related