Adarkas2302 Adarkas2302 - 20 days ago 7
Swift Question

Regular expression that doesn't accept single 0 but does accept 10

I have this regular expression:

^[ 0-9A-Z] [ 0-9]{4}[0-9][/ ][ 0-9A-z]$


and that works fine, but now I have to exclude the 0 in the construct
[ 0-9]{4}[0-9]
in this way.

The string
A 0/A
should get not match

The string
A 10/A
should get a match

So I have to check if the first occurrence of a number in the second group is a
0
or not.

How can I do that?
If anything or everything is not clear, just say so.

Answer

So I have to check if the first occurrence of a number in the second group is a 0 or not.

I think you need a negative lookahead:

^[ 0-9A-Z] (?! *0)[ 0-9]{4}[0-9][/ ][ 0-9A-Za-z]$
           ^^^^^^^

See the regex demo.

Since the [ 0-9]{4}[0-9] matches 4 digits or spaces (there may be just 4 spaces) and the [0-9] matches a digit obligatorily, the (?! *0) will make sure that the pattern above does not match just spaces followed with a 0.