Two regex patterns, can they be single?

I have two regular expressions that I use to check Colorado driver license formats.

[0-9]{2}[-][0-9]{3}[-][0-9]{4}

and

[0-9]{9}

We must allow only 9 digits, but the user can enter it in 123456789 or 12-345-6789.

Is there a way to combine them into one? How to conditional expression regex? Right now, I just list all the available formats and open when one of them maps. I could always remove hyphens before doing a comparison and use only [0-9]{9}, but then I will not learn something new.

+3
source share
4 answers

For direct combining

(?:[0-9]{2}[-][0-9]{3}[-][0-9]{4}|[0-9]{9})

( , ),

[0-9]{2}-?[0-9]{3}-?[0-9]{4}

( .)

, , ,

(?:\d{2}-\d{3}-|\d{5})\d{4}

( [0-9] \d s.)

+12

, :

\d{2}(-?)\d{3}\1\d{4}

Java, , , . Ruby.

+6

, , :

\d{2}(-?)\d{3}\1\d{4}

() "-", . \1 , .

+3

, :

\d{2}-?\d{3}-?\d{4}
0

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


All Articles