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.

Asked By: smart

||

Answers:

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

re.compile(r'^test-d+$')
Answered By: hsz

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.

Answered By: Tom Wyllie

You can try re.findall():

import re
correct_string = 'test-251'

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

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')
Answered By: Rajan saha Raju

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

^ : Start of string

$ : End of string

Answered By: Sandeep PC

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
Answered By: miles82
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.