簡體   English   中英

Java Regex:如何從字符串中提取除最后一部分之外的IP地址?

[英]Java Regex: How to extract ip address except the last part from the string?

我正在嘗試使用websockets ,我想讓它從LAN上的另一台計算機自動連接到本地網絡,因為在同一網絡上有255台可能的計算機,我希望它能夠嘗試所有計算機,然后連接到它可以連接到的第一台計算機。 但是,IP地址的第一部分192.168.1。*根據路由器設置而不同。

我可以得到機器的整個當前IP地址,然后我想提取前面部分。

例如

25.0.0.5 will become 25.0.0.
192.168.0.156 will become 192.168.0.
192.168.1.5 will become 192.168.1.

等等

 String Ip  = "123.345.67.1";
 //what do I do here to get IP == "123.345.67."

你可以使用正則表達式:

String Ip  = "123.345.67.1";
String IpWithNoFinalPart  = Ip.replaceAll("(.*\\.)\\d+$", "$1");
System.out.println(IpWithNoFinalPart);

一個快速的正則表達式解釋: (.*\\\\.)是一個捕獲組,它將所有字符保存到最后. (由於與*量詞的貪婪匹配), \\\\d+匹配1或幾個數字, $是字符串的結尾。

這是TutorialsPoint上示例程序

String Ip  = "123.345.67.1";
String newIp = Ip.replaceAll("\\.\\d+$", "");
System.out.println(newIp);

輸出:

123.345.67

說明:

\.\d+$

Match the character “.” literally «\.»
Match a single character that is a “digit” «\d+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»

演示:

http://ideone.com/OZs6FY

您可以使用String.lastIndexOf('.')來查找最后一個點而不是正則表達式,而使用String.substring(...)來提取第一部分,如下所示:

String ip = "192.168.1.5";
System.out.println(ip.substring(0, ip.lastIndexOf('.') + 1));
// prints 192.168.1.

只需將字符串拆分為“。” 如果字符串是一個有效的IP地址字符串,那么你應該有一個包含4個部分的String []數組,然后你可以只用一個點“。”加入前三個。 並有“前部”



    String IPAddress = "127.0.0.1";
    String[] parts = IPAddress.split(".");

    StringBuffer frontPart = new StringBuffer();
    frontPart.append(parts[0]).append(".")
             .append(parts[1]).append(".")
             .append(parts[2]).append(".");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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