Python regular expression: exact match only

Viewed 86060

I have a very simple question, but I can't find an answer for this.

I have some string like:

test-123

I want to have some smart regular expression for validation if this string exact match my condition.

I expect to have a strings like:

test-<number>

Where number should contains from 1 to * elements on numbers.

I'm trying to do something like this:

import re
correct_string = 'test-251'
wrong_string = 'test-123x'
regex = re.compile(r'test-\d+')
if regex.match(correct_string):
    print 'Matching correct string.'
if regex.match(wrong_string):
    print 'Matching wrong_string.'

So, I can see both messages (with matching correct and wrong string), but I really expect to match only correct string.

Also, I was trying to use search method instead of match but with no luck.

Ideas?

6 Answers

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

^ : Start of string

$ : End of string

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

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')
Related