5

I would like to split a string into parts that match a regexp pattern and parts that do not match into a list.

For example

import re
string = 'my_file_10'
pattern = r'\d+$'
#  I know the matching pattern can be obtained with :
m = re.search(pattern, string).group()
print m
'10'
#  The final result should be as following
['my_file_', '10']

2 Answers 2

12

Put parenthesis around the pattern to make it a capturing group, then use re.split() to produce a list of matching and non-matching elements:

pattern = r'(\d+$)'
re.split(pattern, string)

Demo:

>>> import re
>>> string = 'my_file_10'
>>> pattern = r'(\d+$)'
>>> re.split(pattern, string)
['my_file_', '10', '']

Because you are splitting on digits at the end of the string, an empty string is included.

If you only ever expect one match, at the end of the string (which the $ in your pattern forces here), then just use the m.start() method to obtain an index to slice the input string:

pattern = r'\d+$'
match = re.search(pattern, string)
not_matched, matched = string[:match.start()], match.group()

This returns:

>>> pattern = r'\d+$'
>>> match = re.search(pattern, string)
>>> string[:match.start()], match.group()
('my_file_', '10')
Sign up to request clarification or add additional context in comments.

1 Comment

This definitely answers the original question. Now, I wonder what would be a pythonic way to figure out which elements in the resulting list matched, and which did not. I'd need that, and matching each element to check feels more than a little clunky.
3

You can use re.split to make a list of those separate matches and use filter, which filters out all elements which are considered false ( empty strings )

>>> import re
>>> filter(None, re.split(r'(\d+$)', 'my_file_015_01'))
['my_file_015_', '01']

1 Comment

good idea, but I need something that makes only two parts. For example if the string is 'my_file_015_01', your solution would give ['my_file_', '015', '_', '01']. This complicates things in my code. Martijn's answer suits better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.