'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
有人可以分解所有部分的工作原理吗?尤其是 |1[0-9]{2} 做了什么
'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
有人可以分解所有部分的工作原理吗?尤其是 |1[0-9]{2} 做了什么
(IPv4) IP 地址是一个点分四边形,即 0 到 255 之间的四个数字。
这个正则表达式的意思是“匹配 0 到 255 之间的四个数字,由.
字符分隔。”
正则表达式中的|
字符可以读作“或”,因此每个条目是:
(
[0-9] # a number between 0 and 9
|[1-9][0-9] # or, a number between 10 and 99
|1[0-9]{2} # or, a number between 100 and 199
|2[0-4][0-9] # or, a number between 200 and 249
|25[0-5] # or, a number between 250 and 255
)
\.) # followed by a dot
{3} # three times
([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) # followed by the same match, not followed by a dot
所以这将匹配 和 之间0.0.0.0
的任何内容255.255.255.255
,即任何有效的 IPv4 地址。
经过一番搜索,有一个在线工具可以解释正则表达式:http ://www.myregextester.com/index.php 。在顶部输入您的正则表达式,选中EXPLAIN框,然后点击提交。
它匹配由点分隔的四个数字,其中每个数字介于 0 和 255(含)之间。
让我们分解它以提高可读性:
^ # match the start of the string
( # start capturing group 1
(
[0-9]| # either 0-9, or
[1-9][0-9]| # 1-9 followed by 0-9, i.e. 10-99, or
1[0-9]{2}| # 1 followed by 0-9 followed by 0-9, i.e 100-199, or
2[0-4][0-9]| # 2 followed by 0-4 followed by 0-9, i.e. 200-249, or
25[0-5] # 25 followed by 0-5, i.e. 250-255
)
\. # a dot
){3} # repeat capturing group 1, 3 times
(
[0-9]| # either 0-9, or
[1-9][0-9]| # 1-9 followed by 0-9, i.e. 10-99, or
1[0-9]{2}| # 1 followed by 0-9 followed by 0-9, i.e 100-199, or
2[0-4][0-9]| # 2 followed by 0-4 followed by 0-9, i.e. 200-249, or
25[0-5] # 25 followed by 0-5, i.e. 250-255
)
$ # match the end of the string
管道字符|
是OR
运算符。
{n}
意思是:“重复以前发生的任何事情n
”。
你能看出为什么正则表达式的后半部分在那里吗?为什么我们不能重复前半部分4
而不是重复3
?
[0-9] 可接受值的范围。在这种情况下 0-9 {} 这是一个正则表达式量词。例如 {2} 表示正好 2 个字符。| 这是或。例如 a|b 是 OR b。^ 字符串开头 $ 字符串结尾
所以 |1[0-9]{2} 表示数字“1”后跟 0-9 范围内的 2 位数字。
在这里查看正则表达式的快速参考