匹配各种数字
[a-b]
其中 a 和 b 是 0
到 9
范围内的数字
[3-7] will match a single digit in the range 3 to 7.
匹配多个数字
\d\d will match 2 consecutive digits
\d+ will match 1 or more consecutive digits
\d* will match 0 or more consecutive digits
\d{3} will match 3 consecutive digits
\d{3,6} will match 3 to 6 consecutive digits
\d{3,} will match 3 or more consecutive digits
以上示例中的\d
可以替换为数字范围:
[3-7][3-7] will match 2 consecutive digits that are in the range 3 to 7
[3-7]+ will match 1 or more consecutive digits that are in the range 3 to 7
[3-7]* will match 0 or more consecutive digits that are in the range 3 to 7
[3-7]{3} will match 3 consecutive digits that are in the range 3 to 7
[3-7]{3,6} will match 3 to 6 consecutive digits that are in the range 3 to 7
[3-7]{3,} will match 3 or more consecutive digits that are in the range 3 to 7
你还可以选择特定的数字:
[13579] will only match "odd" digits
[02468] will only match "even" digits
1|3|5|7|9 another way of matching "odd" digits - the | symbol means OR
匹配包含多个数字的范围中的数字:
\d|10 matches 0 to 10 single digit OR 10. The | symbol means OR
[1-9]|10 matches 1 to 10 digit in range 1 to 9 OR 10
[1-9]|1[0-5] matches 1 to 15 digit in range 1 to 9 OR 1 followed by digit 1 to 5
\d{1,2}|100 matches 0 to 100 one to two digits OR 100
匹配除以其他数字的数字:
\d*0 matches any number that divides by 10 - any number ending in 0
\d*00 matches any number that divides by 100 - any number ending in 00
\d*[05] matches any number that divides by 5 - any number ending in 0 or 5
\d*[02468] matches any number that divides by 2 - any number ending in 0,2,4,6 or 8
匹配的数字除以 4 - 任何数字为 0,4 或 8 或结束于 00,04,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92 或 96
[048]|\d*(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)
这可以缩短。例如,我们可以使用 2[048]
代替 20|24|28
。此外,由于 40 年代,60 年代和 80 年代具有相同的模式,我们可以包括它们:[02468][048]
和其他的模式太 [13579][26]
。所以整个序列可以减少到:
[048]|\d*([02468][048]|[13579][26]) - numbers divisible by 4
匹配的数字不具有可被 2,4,5,10 等整除的模式,但不能总是简洁地完成,你通常不得不求助于一系列数字。例如,通过列出所有这些数字,可以简单地匹配在 1 到 50 范围内除以 7 的所有数字:
7|14|21|28|35|42|49
or you could do it this way
7|14|2[18]|35|4[29]