繁体   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