Maulik Parekh
Maulik Parekh

Reputation: 39

Why is python matching the wrong pattern?

import re
look = r'Template.11_31.Single-Volume'
pattern = r'11.31'

match = re.search(pattern,look)

print re.findall(pattern,look)

if (match is not None):
    print match.group(0)

Answer:

['11_31']
11_31

I want it to match 11.31 or 1131 but here it also matches 11_31

Upvotes: 0

Views: 69

Answers (2)

vks
vks

Reputation: 67968

pattern =r'11.31'

Here . can match anything so it will match _ in 11_31 as well. Either escape it (\.) or put it in character class ([.]) and add more to it as when required.

Use this

pattern =r'11[.]?31'

See demo.

https://regex101.com/r/sH8aR8/21

Upvotes: 3

anubhava
anubhava

Reputation: 784998

Problem is in your regex 11.31 dot will match any character.

You can use this regex:

pattern = r'11\.?31'

This will match 11.31 or 1131 but not 11_31 or 11:31 since \. matches a literal dot and \.? makes dot an optional match.

Example:

>>> print re.findall(pattern, "Template.11.31.Single-Volume-1131-something")
['11.31', '1131']

Upvotes: 5

Related Questions