正则表达式上的Python拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4995892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python split string on regex
提问by Jared Knipp
I'm trying to split a string using a regular expression.
我正在尝试使用正则表达式拆分字符串。
Friday 1Friday 11 JAN 11
The output I want to achieve is
我想要实现的输出是
['Friday 1', 'Friday 11', ' JAN 11']
My snippet so far is not producing the desired results:
到目前为止,我的代码片段没有产生预期的结果:
>>> import re
>>> p = re.compile(r'(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*\d{1,2}')
>>> filter(None, p.split('Friday 1Friday 11 JAN 11'))
['Friday', 'Friday', ' JAN 11']
What am I doing wrong with my regex?
我的正则表达式做错了什么?
采纳答案by scoffey
The problem is the capturing parentheses. This syntax: (?:...)makes them non-capturing. Try:
问题是捕获括号。此语法:(?:...)使它们无法捕获。尝试:
p = re.compile(r'((?:Friday|Saturday)\s*\d{1,2})')
回答by Asterisk
p = re.compile(r'(Friday\s\d+|Saturday)')
回答by sateesh
You can also use 're.findall' function.
您还可以使用“re.findall”功能。
\>>> val
'Friday 1Friday 11 JAN 11 '
\>>> pat = re.compile(r'(\w+\s*\d*)')
\>>> m=re.findall(pat,val)
\>>> m
['Friday 1', 'Friday 11', 'JAN 11']

