我正在试验 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 个或多个数字,并且 $
是字符串的结尾。
关于Java 正则表达式 : How to extract ip address except the last part from the string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019042/