Regex for fixed width field

I need to map a fixed width field in a file layout to a regular expression. The field is numeric / integer, always has four characters and is in the range 0..1331. When the number is less than 1000, the string is filled with left zeros. So, all these examples are valid:

  • 0000
  • 0001
  • 0010
  • 1000
  • 1331

But the following should not be accepted:

  • 1
  • 01
  • 10
  • one hundred
  • 4759

It would be nice if I could apply this restriction only with regex. After playing a little, I gave expression \0*[0-1331]\. The problem is that it does not limit the size to four characters. Of course, I could do \000[0-9]|00[10-99]|0[100-999]|[1000-1331]\, but I refuse to use something so nasty. Can anyone think of a better way?

+3
2

. : - :

boolean isValidSomethingOrOther (string):
    if string.length() != 4:
        return false
    for each character in string:
        if not character.isNumeric():
            return false
    if string.toInt() > 1331:
        return false
    return true

, , , , ( RE , ):

^0[0-9]{3}|1[0-2][0-9]{2}|13[0-2][0-9]|133[01]$
  • 0000-0999.
  • 1000-1299.
  • 1300-1329.
  • 1330 1331.

Update:

, , - . , , :

if isValidSomethingOrOther(str) ...

SomethingOrOther - -. , , (, ).

, , .

, "prime-number-less-than-1332". , - ( ), , , , :

^2|3|5|7| ... |1327$

.

+7

, ?

\[01][0-9]{3}\

, .. , ? - .

, :

In [3]: r = re.compile(r'[01][0-9]{3}')

In [4]: r.match('0001')
Out[4]: <_sre.SRE_Match object at 0x2fa2d30>

In [5]: r.match('1001')
Out[5]: <_sre.SRE_Match object at 0x2fa2cc8>

In [6]: r.match('2001')

In [7]: r.match('001')

In [8]: 
+1

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


All Articles