[英]tcl regex match ip address in a single line
i am trying to write a regexp which will check whether the ip is valid or not.Facing issue when i give 256 as value it is still matching 2, and reg will store the value as 1 since the pattern is matched. 我正在尝试编写一个正则表达式,它将检查ip是否有效。面对问题,当我给出256作为值时,它仍与2匹配,并且由于模式已匹配,因此reg将值存储为1。
set ip "256.256.255.1"
set reg [regexp -all{^([1-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([1-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([1-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([1-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])} $ip match ]
puts $reg
The unescaped .
无人逃脱
.
will match any character, not just a .
可以匹配任何字符,而不仅仅是
.
symbol. 符号。 The capturing groups are unnecessary since you are only interested in 1 whole match.
捕获组是不必要的,因为您只对1个完整比赛感兴趣。 Besides, no need to use
-all
since you want to validate a single string. 此外,无需使用
-all
因为您要验证单个字符串。
Use 采用
set text {256.256.255.1}
set pattern {^(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}$}
regexp $pattern $text match
if {[info exists match]} {
puts $match
} else {
puts "No match"
}
See the online Tcl demo . 参见在线Tcl演示 。
Pattern details : 图案细节 :
^
- start of string ^
-字符串开头 (?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
- first octet matching numbers from 0
to 255
(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
-从0
到255
第一个八位位组匹配数字 (?:\\.(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}
- 3 occurrences of a .
(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}
-3次出现.
(see \\.
) and the octet subpattern \\.
)和八位位组子模式 $
- end of string. $
-字符串结尾。 For very complicated regexes, breaking it into pieces help readability: 对于非常复杂的正则表达式,将其分成几部分有助于提高可读性:
set octet {(?:[1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])}
set ip_re [format {\m%s\.%s\.%s\.%s\M} {*}[lrepeat 4 $octet]]
Note, your regex will not match octets 10 to 99 or 0. 请注意,您的正则表达式将与10到99或0的八位字节不匹配。
testing 测试
set str "hello 1.2.3.4 there 127.0.0.1 friend 256.9.99.999 x255.255.255.255"
regexp -all $ip_re $str ;# => 2
regexp -all -inline $ip_re $str ;# => 1.2.3.4 127.0.0.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.