Python 3正则表达式Issu

2024-10-01 02:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么下面的string1regexp不匹配?我已经用this对它进行了测试,似乎我的正则表达式fu是准确的,所以我想我在python实现中肯定遗漏了一些东西:

import re
pattern = r".*W([0-9]+(\.5)?)[^\.]?.*$"
string1 = '6013-SFR6W4.5'
string2 = '6013-SFR6W4.5L'
print(re.match(pattern, string1)) # the return value is None
print(re.match(pattern, string2)) # this returns a re.match object

Here是显示此问题的交互式会话的屏幕截图。你知道吗

编辑

你知道吗系统版本产出3.4.3


Tags: theimportrereturnisvaluematchthis
3条回答

我尝试了完全相同的代码,两种情况下我都匹配:

Python3.4:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> pattern = r".*W([0-9]+(\.5)?)[^\.]?.*$"
>>> string1 = '6013-SFR6W4.5'
>>> print(re.match(pattern, string1))
<_sre.SRE_Match object; span=(0, 13), match='6013-SFR6W4.5'>
>>> string2 = '6013-SFR6W4.5L'
>>> print(re.match(pattern, string2))
<_sre.SRE_Match object; span=(0, 14), match='6013-SFR6W4.5L'>

python 2.7版:

Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> pattern = r".*W([0-9]+(\.5)?)[^\.]?.*$"
>>> string1 = '6013-SFR6W4.5'
>>> print(re.match(pattern, string1))
<_sre.SRE_Match object at 0x10abf83e8>
>>> string2 = '6013-SFR6W4.5L'
>>> print(re.match(pattern, string2))
<_sre.SRE_Match object at 0x10abf83e8>

尝试使用pattern = r"^.*W([0-9]+(\.5)?)[^\.]?.*$",在开头加上^。你知道吗

在您发布的代码中,您有:

pattern = r".*W([0-9]+(\.5)?)[^\.]?.*$"

但是在你截图上的代码里

pattern = r".*W([0-9]+(\.5)?)[^\.]+.*$"

(注意,第一个模式末尾附近的?被第二个模式中的+替换)

当我运行您提供的代码时,会得到以下两个方面的返回值:

$ python3 test.py
<_sre.SRE_Match object at 0x6ffffedc3e8>
<_sre.SRE_Match object at 0x6ffffedc3e8>

相关问题 更多 >