Is the best way to match two different repetitions of the same character class in a regular expression?

I used [0-9]{9,12} all the time to indicate that the number string is 9 or 12 characters long. However, now I realized that it would correspond to input strings of length 10 or 11. Therefore, I came out naive:

 ( [0-9]{9} | [0-9]{12} ) 

Is there a more concise regex to represent this?

+6
source share
3 answers

You can save one character using

 [0-9]{9}([0-9]{3})? 

but, in my opinion, your path is better, because it more clearly conveys your intention. Regexes is hard to read already.

Of course, you can use \d instead of [0-9] .

(Edit: At first, I thought you could drop the parens around [0-9]{3} , but you cannot, the question mark will be ignored. This way you only save one character, not three.)

(Edit 2: you also need to bind the regex with ^ and $ (or \b ) or re.match() , will also match 123456789 inside 1234567890 )

+7
source

you may try

 (\d{9}\d{3}?) 

to match 9 and then an extra 3 digits

or

 ((\d{3}){3,4}) 

to match 3 or four groups of 3 digits

+6
source

You can do it:

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

Not so much...

+1
source

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


All Articles