Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expression: exact match only

Tags:

python

regex

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?

like image 202
smart Avatar asked Jul 21 '17 18:07

smart


People also ask

How do I capture a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do you use exact match in Python?

Exact match (equality comparison): == , != It is case-sensitive, and the same applies to comparisons by other operators and methods. Case-insensitive comparisons are described later. != returns True if they are not equal, and False if they are equal.

How do you match exact strings?

We can match an exact string with JavaScript by using the JavaScript string's match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.


1 Answers

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

re.compile(r'^test-\d+$') 
like image 159
hsz Avatar answered Sep 21 '22 15:09

hsz