[英]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.我一直使用
[0-9]{9,12}
来表示数字字符串的长度为 9 或 12 个字符。 However I now realized that it will match input strings of length 10 or 11 as well.但是我现在意识到它也会匹配长度为 10 或 11 的输入字符串。 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]
.当然,您可以使用
\d
而不是[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.) (编辑:我首先认为您可以将括号放在
[0-9]{3}
附近,但您不能;问号将被忽略。所以您只保存一个字符,而不是三个。)
(Edit 2: You will also need to anchor the regex with ^
and $
(or \b
) or re.match()
will also match 123456789
within 1234567890
.) (编辑 2:您还需要使用
^
和$
(或\b
)锚定正则表达式,否则re.match()
也将匹配123456789
内的1234567890
。)
you could try你可以试试
(\d{9}\d{3}?)
to match 9 and then an optional extra 3 digits匹配 9,然后是可选的额外 3 位数字
or或者
((\d{3}){3,4})
to match 3 or four groups of 3 digits匹配 3 组或 4 组 3 位数字
You could do this:你可以这样做:
[0-9]{9}[0-9]{3}?
Not much different is it...没有太大的不同吧...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.