27
votes

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

6 Answers

40
votes

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

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

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

^ : Start of string

$ : End of string

5
votes

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
3
votes

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')
2
votes

You can try re.findall():

import re
correct_string = 'test-251'

if len(re.findall("test-\d+", correct_string)) > 0:
    print "Match found"
0
votes

A pattern such as \btest-\d+\b should do you;

matches = re.search(r'\btest-\d+\', search_string)

Demo

This requires the matching of word boundaries, so prevents other substrings from occuring after your desired match.