Python regular expression: exact match only

Since Python 3.4 you can use re.fullmatch to avoid adding ^ and $ to your pattern.

>>> import re
>>> p = re.compile(r'\d{3}')
>>> bool(p.match('1234'))
True

>>> bool(p.fullmatch('1234'))
False

For exact match regex = r'^(some-regex-here)$'

^ : Start of string

$ : End of string


Try with specifying the start and end rules in your regex:

re.compile(r'^test-\d+$')

I think It may help you -

import re
pattern = r"test-[0-9]+$"
s = input()

if re.match(pattern,s) :
    print('matched')
else :
    print('not matched')

Tags:

Python

Regex