2013-01-06 33 views
0

我需要的正則表達式檢測所有IP地址與端口和端口沒有,但除外正則表達式與例外

93.153.31.151(:27002)

10.0。 0.1(:27002)

我有一些,但我需要添加異常

\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d{1,5})? 

對於Java匹配

String numIPRegex = "\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d{1,5})?"; 

    if (pA.matcher(msgText).find()) { 
     this.logger.info("Found"); 

    } else {  
     this.logger.info("Not Found");     

    } 
+2

正則表達式在這裏似乎不是正確的選擇。你有'InetAddress',它可以檢測正確的格式化地址,''可以解析整數的Integer.parseInt()','String'中的'indexOf()'。而且,如果你使用番石榴,你也有'HostAndPort'。 – fge

+0

@fge什麼'SocketAddress'? –

+0

另外你也不應該忘記IPv6地址。 –

回答

4

未做有關可在一個結構化的方式來處理IP addreses更適合的Java類的聲明...

可以使用負查找aheads例外添加到正則表達式:

String numIPRegex = "(?!(?:93\\.153\\.31\\.151|10\\.0\\.0\\.1)(?::27002)?)\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d{1,5})?"; 

說明:

 
(?!         # start negative look-ahead 
    (?:         # start non-capturing group 
    93\.153\.31\.151     #  exception address #1 
    |         #  or 
    10\.0\.0\.1      #  exception address #2 
)         # end non-capturing group 
    (?:         # start non-capturing group 
    :27002       #  port number 
)?         # end non-capturing group; optional 
)          # end negative look-ahead 
\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})? # your original expression 

當然其他明顯的替代將是一個測試異常的前期一個,只是返回false,如果一個例外相匹配。將它們全部包裝在一個大的正則表達式中會很快變得非常難看。

+0

對於隱含的「你不應該使用正則表達式來表達這樣的東西」以及提供教育答案。 –

0

你想要這個嗎?

public static void main(String[] args) { 
    System.out.println(match("93.153.31.151(:27002)")); // false 
    System.out.println(match("12.23.34.45(:21002)")); // true 
} 
public static boolean match(String input) { 
    String exclude = "|93.153.31.151(:27002)|10.0.0.1(:27002)|"; 
    if (exclude.contains("|" + input + "|")) return false; // Exclude from match 
    // 
    String numIPRegex = "^\\d{1,3}(\\.\\d{1,3}){3}\\(:\\d{1,5}\\)$"; 
    Pattern pA = Pattern.compile(numIPRegex); 
    // 
    if (pA.matcher(input).matches()) { 
     System.out.println("Found"); 
     return true; 
    } else {  
     System.out.println("Not Found");     
    } 
    return false; 
}