使用正则表达式在 Python 中拆分字符串 [英] String splitting in Python using regex
问题描述
我正在尝试在 Python 中拆分一个字符串,以便在某个正则表达式之前获得所有内容.
I'm trying to split a string in Python so that I get everything before a certain regex.
示例字符串:"Some.File.Num10.example.txt"
我需要这部分之前的所有内容:"Num10"
,正则表达式:r'Num\d\d'
(数字会有所不同,后面可能会有所不同).
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?
推荐答案
>>> 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.
我刚刚写了一个小程序来分析 search() 和 split() 并证实了上述断言.
I just wrote a small program to profile search() and split() and confirmed the above assertion.
这篇关于使用正则表达式在 Python 中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!