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?
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.
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.
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.
Try with specifying the start and end rules in your regex:
re.compile(r'^test-\d+$')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With