簡體   English   中英

如何在Android中提取IP地址的前三段

[英]How to extract the first three segments of an IP address in android

例:

xxx.xxx.xxx.xxx是IP地址格式,我只想獲取前三個段(帶點):xxx.xxx.xxx。

另一個例子:

192.168.0.160,我只需要192.168.0。

String[] splittedArray = ipAddressString.split("\\.");
String firstThreeSegments = splittedArray [0] + "." + splittedArray [1] + "." + splittedArray [2] + ".";
String partialIp = ipAddress.substring(0, ipAddress.lastIndexOf(".")+1);

您可以使用String#replaceFirst

String firstThree = ip.replaceFirst("\\d+$", "");

這將替換任何有效IP地址的最后一部分,並用空字符串替換。

正則演示

我想說的最簡單的方法(IMO)是使用(來自Apache Commons) StringUtils.ordinalIndexOf()查找第三個時間段的索引值,然后使用substring()將子字符串從0轉換為該索引值。

例如:

StringUtils.ordinalIndexOf("192.168.0.160", ".", 3)  == 9

然后,您可以使用此索引獲取子字符串。

暫無
暫無

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

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