2015-07-12 82 views
1

我有以下字符串:正则表达式不捕获所有信息

a = '''"The cat is running to the door, he does not look hungry anymore". 

Said my mom, whispering.''' 

注意换行符。在Python中的字符串将是: 'The cat is running to the door, he does not look hungry anymore".\n \n Said my mom, whispering.'

我有这样的正则表达式: pattern = u'^("|«)(.*?)("|»)(.*?)\u000A{1,}(.*?)'

,我作为在Python如下:

>>> import re 
>>> a = '''"The cat is running to the door, he does not look hungry anymore". 

Said my mom, whispering.''' 
>>> pattern = u'^("|«)(.*?)("|»)(.*?)\u000A{1,}(.*?)' 
>>> re.search(pattern, a).groups() 
>>> ('"', 'The cat is running to the door, he does not look hungry anymore', '"', '.', '') 

为什么最后一部分(Said my mom, whispering.)是不是被被正则表达式抓住了? 我期待这样的事情:

>>> ('"', 'The cat is running to the door, he does not look hungry anymore', '"', '.', 'Said my mom, whispering.') 

能否请您澄清我,我做错了什么?

+0

这不是全球性的? – Downgoat

+0

变量'a'? @ vihan1086 – gglasses

+0

[regex101](https://regex101.com/#python)正则表达式测试程序可以真正有助于调试正则表达式代码。 – tegancp

回答

1

刚取出?就足够了。并且最好包含DOTALL修饰符,因为默认情况下,正则表达式中的点不会匹配换行符。

pattern = u'(?s)^("|«)(.*?)("|»)(.*?)\u000A{1,}(.*)' 

注意.*?不愿意或非贪婪这意味着零次或多次匹配任何字符非贪婪地。所以一旦找到空字符串就停止匹配。

+0

为了确保我得到了正确的结果,使用:'(。*)'我会抓住一切,从一个空间到很多空间和任何其他角色,'贪婪',对吧?什么是'(?s)'? – gglasses

+0

'。*'默认不匹配换行符。 '(?s)'叫做DOTALL修饰符,它使点进入正则表达式以匹配换行符。 –

+0

太棒了!非常感谢,现在更清晰了。因为我预计第一组会有一些换行符,最后一组会有更多换行符。 – gglasses

0

与表达的问题是,(.*?)不愿意,这意味着它应尽可能少的文字尽可能匹配。由于您不要求匹配在输入末尾处“锚定”,因此第二组为空。

在表达式的末尾添加$将解决这个问题:

pattern = u'^("|«)(.*?)("|»)(.*?)\u000A{1,}(.*?)$' 
0

您的输入不以引号开头,正则表达式需要它。然后,第二行缺少一个换行模式。第三,.*?懒惰匹配不会匹配任何东西,因为它可以匹配空字符串,所以如果您不使用锚点$或使用贪婪匹配。

另外,在变化中使用单个字母效率不高,所以我宁愿在这种情况下使用字符类:("|«) =>["«]

随着\s速记课程,您不仅可以匹配换行符,还可以匹配空格,从而“捕获”捕获组中的结果。

这里是我的建议:

import re 
p = re.compile(r'^(["«])?(.*?)(["»])?\.\s*(.*?)\s*(.*)') 
test_str = "The cat is running to the door, he does not look hungry anymore\".\n\nSaid my mom, whispering." 
print re.search(p, test_str).groups() 

demo