A regular expression must contain and can only contain

I want a regular expression for python that matches a string that must contain 4 digits, it may not contain any special characters other than "-" or ".", And may contain only capital letters. I know the following text with four digits or more. How to add other 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, as it contains a lowercase char and a special char, which is not a "-" or "."

+4
source share
1 answer

Sample:

pattern = '^[A-Z.-]*(\d[A-Z.-]*){4,}$'
  • ^ -
  • [A-Z.-]* - " ": ,
  • (\d[A-Z.-]*){4,} - 4 " "; 4
  • $ -

:

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'>
+5

Source: https://habr.com/ru/post/1694271/


All Articles