0
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

1
  • maybe I am not answering your question, but you will like this syntax sugar: print "".join(match.group(0) if match is not None else "") Commented Jan 8, 2015 at 7:03

2 Answers 2

5

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']
Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.