I want a regular expression for python that matches a string which must contain 4 digits, it may not contain any special character other than "-" or ".", and it may only contain uppercase letters. I know the following matches text with 4 digits or more. How would I add the rest of the criteria?
[0-9]{4,}
An example would be: ART-4.5-11 is good, ART5411 is good, 76543 is good, but aRT-4!5-11 is bad since it contains a lowercase char and a special char that is not "-" or "."
$ means "Match the end of the string" (the position after the last character in the string).
[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.
NOT REGEXP in MySQL is a negation of the REGEXP operator used for pattern matching. It compares the given pattern in the input string and returns the result, which does not match the patterns. If this operator finds a match, the result is 0.
Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.
The pattern:
pattern = '^[A-Z.-]*(\d[A-Z.-]*){4,}$'
^
- start of the word[A-Z.-]*
- any number of optional non-digit "good characters": letters, periods or dashes(\d[A-Z.-]*){4,}
- 4 or more groups of a digit and other "good characters"; this part provides at least 4 digits$
- end of the wordExamples:
re.match(pattern, "ART-4.5-11")
# <_sre.SRE_Match object; span=(0, 10), match='ART-4.5-11'>
re.match(pattern, "ART5411")
# <_sre.SRE_Match object; span=(0, 7), match='ART5411'>
re.match(pattern, "aRT-4!5-11") # No match
re.match(pattern, "76543")
# <_sre.SRE_Match object; span=(0, 5), match='76543'>
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