简体   繁体   中英

Is the better way to match two different repetitions of the same character class in a regex?

I had been using [0-9]{9,12} all along to signify that the numeric string has a length of 9 or 12 characters. However I now realized that it will match input strings of length 10 or 11 as well. So I came out with the naive:

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

Is there a more succinct regex to represent this?

You could save one character by using

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

but in my opinion your way is better because it conveys your intention more clearly. Regexes are hard enough to read already.

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

(Edit: I first thought you could drop the parens around [0-9]{3} but you can't; the question mark will be ignored. So you only save one character, not three.)

(Edit 2: You will also need to anchor the regex with ^ and $ (or \b ) or re.match() will also match 123456789 within 1234567890 .)

you could try

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

to match 9 and then an optional extra 3 digits

or

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

to match 3 or four groups of 3 digits

You could do this:

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

Not much different is it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM