Regex 有人能分析一下匹配IP的正则表达式是如何工作的吗
有人能解释一下所有部件的工作原理吗?特别是| 1[0-9]{2}所做的事情(IPv4)IP地址是一个虚线四元组,即0到255之间的四个数字 这个正则表达式的意思是“匹配0和255之间的四个数字,用Regex 有人能分析一下匹配IP的正则表达式是如何工作的吗,regex,Regex,有人能解释一下所有部件的工作原理吗?特别是| 1[0-9]{2}所做的事情(IPv4)IP地址是一个虚线四元组,即0到255之间的四个数字 这个正则表达式的意思是“匹配0和255之间的四个数字,用字符分隔。” 正则表达式中的|字符可以读作“or”,因此每个条目都是: '^(([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])$ 因此,这将匹配0
字符分隔。”
正则表达式中的|
字符可以读作“or”,因此每个条目都是:
'^(([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])$
因此,这将匹配0.0.0.0
和255.255.255.255
之间的任何内容,即任何有效的IPv4地址
做了一些搜索之后,有一个在线工具可以解释正则表达式:。在顶部输入正则表达式,选中解释框,然后点击提交。[0-9]接受值的范围。在这种情况下为0-9 {}这是一个正则表达式量词。例如{2}表示正好两个字符。 |这是或。例如a | b是a或b。 ^字符串开头 $字符串结尾 因此| 1[0-9]{2}表示数字“1”后跟0-9范围内的2位数字
查找regex的快速引用它匹配四个由点分隔的数字,每个数字都在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
管道字符|
是或运算符。
{n}
的意思是:“重复n
次之前发生的任何事情”
你能指出为什么regexp的后半部分在那里吗?为什么我们不能把前半部分的4
重复一遍,而不是3
?|1[0-9]{2}表示“1”或“1”后跟2个数字”
^ # 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