11

I'm trying to split a string in Python so that I get everything before a certain regex.

example string: "Some.File.Num10.example.txt"

I need everything before this part: "Num10", regex: r'Num\d\d' (the number will vary and possibly what comes after).

Any ideas on how to do this?

3 Answers 3

13
>>> import re
>>> s = "Some.File.Num10.example.txt"
>>> p = re.compile("Num\d{2}")
>>> match = p.search(s)
>>> s[:match.start()]
'Some.File.'

This would be more efficient that doing a split because search doesn't have to scan the whole string. It breaks on the first match. In your example it wouldn't make a different as the strings are short but in case your string is very long and you know that the match is going to be in the beginning, then this approach would be faster.

I just wrote a small program to profile search() and split() and confirmed the above assertion.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use p = re.compile("Num\d") simply as number can be anything so we are just concerned when it starts in the string.
10
>>> import re
>>> text = "Some.File.Num10.example.txt"
>>> re.split(r'Num\d{2}',text)[0]
'Some.File.'

Comments

5

You can use Python's re.split()

import re

my_str = "This is a string."

re.split("\W+", my_str)

['This', 'is', 'a', 'string', '']

Comments

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.