How can I make a regex match the entire string?
Question:
Suppose I have a string like test-123
.
I want to test whether it matches a pattern like test-<number>
, where <number>
means one or more digit symbols.
I tried this code:
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.'
How can I make it so that only the correct_string
matches, and the wrong_string
doesn’t? I tried using .search
instead of .match
but it didn’t help.
Answers:
Try with specifying the start and end rules in your regex:
re.compile(r'^test-d+$')
A pattern such as btest-d+b
should do you;
matches = re.search(r'btest-d+', search_string)
This requires the matching of word boundaries, so prevents other substrings from occuring after your desired match.
You can try re.findall()
:
import re
correct_string = 'test-251'
if len(re.findall("test-d+", correct_string)) > 0:
print "Match found"
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')
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
Suppose I have a string like test-123
.
I want to test whether it matches a pattern like test-<number>
, where <number>
means one or more digit symbols.
I tried this code:
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.'
How can I make it so that only the correct_string
matches, and the wrong_string
doesn’t? I tried using .search
instead of .match
but it didn’t help.
Try with specifying the start and end rules in your regex:
re.compile(r'^test-d+$')
A pattern such as btest-d+b
should do you;
matches = re.search(r'btest-d+', search_string)
This requires the matching of word boundaries, so prevents other substrings from occuring after your desired match.
You can try re.findall()
:
import re
correct_string = 'test-251'
if len(re.findall("test-d+", correct_string)) > 0:
print "Match found"
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')
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