Reputation: 1002
Why does the following string1
regexp not match? I have tested it using this and it appears my regex-fu is accurate, so I figure I must be missing something in the python implementation:
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 is a screenshot of an interactive session showing this issue.
EDIT
sys.version outputs 3.4.3
Upvotes: 3
Views: 69
Reputation: 819
I've tried the exact same code and I have a match for both cases:
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>
Try use pattern = r"^.*W([0-9]+(\.5)?)[^\.]?.*$"
, with ^
at the beginning.
Upvotes: 1
Reputation: 12869
In the code you posted, you have:
pattern = r".*W([0-9]+(\.5)?)[^\.]?.*$"
But in the code from your screenshot, you have
pattern = r".*W([0-9]+(\.5)?)[^\.]+.*$"
(Note the ?
near the end of the first pattern is replaced with a +
in the second one)
Upvotes: 1
Reputation: 1283
When I run the code you provided, I get return values on both:
$ python3 test.py
<_sre.SRE_Match object at 0x6ffffedc3e8>
<_sre.SRE_Match object at 0x6ffffedc3e8>
Upvotes: 1