我想构建一个与逗号(,
)分隔的IP字符串匹配的RegEx,或者字符串只有*
。字符串不应该同时具有IP地址和*
验证IP,即1.1.1.1
(数字和.
点字符)。此外,仅允许*
*
存在,不存在其他IP。
这是正则表达式
(((25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)(,\n|,?))|(,*))
测试字符串:
192.168.1.1,192.56.3.23,189.35.2.2,198.23.45.56,198.168.1.255
如何查看*
?
答案 0 :(得分:1)
您可以使用
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|\*)(?:,\s*(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|\*))*$
请参见regex demo
Expanded//verbose/free-spacing version:
^ # start of string
(?: # start of a grouping
(?: # start of another grouping
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # First octet and .
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Second octet and .
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Third octet and .
(?:25[0-5]|2[0-4]\d|[01]?\d\d?) # Fourth octet
|\* # or just a * char instead of an IP
) # end of another grouping
) # end of grouping
(?:,\s* # a group that will repeat 0+ times, matches , then 0+ whitespaces
(?: # an IP matching grouping
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # First octet and .
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Second octet and .
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Third octet and .
(?:25[0-5]|2[0-4]\d|[01]?\d\d?) # Fourth octet
|\*) # Or a *
)* # ... zero or more times
$ # end of string