Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression must contain and may only contain

Tags:

python

regex

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 "."

like image 612
p192 Avatar asked Mar 01 '18 00:03

p192


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What's the difference between () and [] in regular expression?

[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.

What is not in regular expression?

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.

How do I allow all items in regex?

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.


1 Answers

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 word

Examples:

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'>
like image 79
DYZ Avatar answered Oct 18 '22 04:10

DYZ