簡體   English   中英

tcl regex在一行中匹配IP地址

[英]tcl regex match ip address in a single line

我正在嘗試編寫一個正則表達式,它將檢查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

無人逃脫. 可以匹配任何字符,而不僅僅是. 符號。 捕獲組是不必要的,因為您只對1個完整比賽感興趣。 此外,無需使用-all因為您要驗證單個字符串。

采用

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"
}

參見在線Tcl演示

圖案細節

  • ^ -字符串開頭
  • (?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) -從0255第一個八位位組匹配數字
  • (?:\\.(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3} -3次出現. (請參閱\\. )和八位位組子模式
  • $ -字符串結尾。

對於非常復雜的正則表達式,將其分成幾部分有助於提高可讀性:

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]]

請注意,您的正則表達式將與10到99或0的八位字節不匹配。

測試

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM