我在这里看到一些很长的正则表达式。这项任务可以在您的模式中没有大量冗余的情况下解决。如果您除了正则表达式之外没有其他任何东西可以使用,那么这就是您想要的模式:
^(([123][1-9]|[234]0)[0-9]{3}|10([5-9][0-9]{2}|4([3-9][0-9]|29)))$
在这里它被扩展以向您展示它的含义:
^ #The beginning of the line. This ensures 10429 passes, but 9999910429 doesn't.
(
([123][1-9]|[234]0) #This lets the first two digits be anything from 11-40. We'll deal with 10xxx later on.
[0-9]{3} #If the first two digits are 11-40, then the last three can be anything from 000-999.
|
10 #Okay, we've covered 11000-40999. Now for 10429-10999.
(
[5-9][0-9]{2} #Now we've covered 10500-10999; on to the 104xx range.
|
4
(
[3-9][0-9] #Covers 10430-10499.
|
29 #Finally, the special case of 10429.
)
)
)
$ #The end of the line. This ensures 10429 passes, but 104299999 doesn't.
如果数字不是整个输入,而是嵌入在字符串中(例如,您想从字符串“blah blah 11000 foo 39256 bar 22222”中获取所有数字,请将^
和$
替换为\b
.
看到它在 Regexr 上工作:http: //regexr.com?312p0