简体   繁体   English

为什么以下正则表达式在Python中不起作用?

[英]why the following regular expression does not work in Python?

I am trying to use some regex in python for pattern matching. 我正在尝试在python中使用一些正则表达式进行模式匹配。 I am looking at a very simple example, but this does not work as I expected. 我正在看一个非常简单的示例,但这并不符合我的预期。 the snippet is as follows. 片段如下。 I expected it to print "match", but it did not 我希望它能打印“匹配”,但没有

>>> line="123 a bcdef12"
>>> data_headers = re.compile('.*a bc.* ')
>>> if data_headers.match(line):
...     print "match"
... 
>>> 

I also tried the following: 我还尝试了以下方法:

>>> data_headers = re.compile(' a bc* ')
>>> data_headers = re.compile('.*a bc* ')

but both did not find any match. 但都没有找到任何匹配。

Any suggestions are welcome. 欢迎任何建议。 Thanks 谢谢

The space at the end is what's stopping it from matching: 最后的空格是阻止其匹配的原因:

>>> import re
>>> re.match(".*a bc.* ", "123 a bcdef12")
None
>>> re.match(".*a bc.*", "123 a bcdef12")
<_sre.SRE_Match object at 0x7fdd6c462b90>

You might find a tool such as debuggex (there are many others) useful for testing and debugging regex expressions. 您可能会发现诸如debuggex之类的工具(还有许多其他工具)对于测试和调试regex表达式很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM