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 t开发者_运维知识库o 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...
精彩评论