簡體   English   中英

從IP地址提取前三個八位字節

[英]Extract first three octet from IP address

我需要從IP地址(C類)中提取前三個八位位組,並且可以通過分割"//."來做到這一點"//." 但是有沒有辦法使用REGEX做到這一點。

輸入: 192.168.1.1輸出: 192.168.1

像這樣:

/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/

使用匹配就可以了。

對於Java更精確:

Pattern p = Pattern.compile("([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3}).*");
Matcher m = p.matcher("127.0.2.13");
if (m.matches()) {
    String s0 = m.group(1);   // contains "127"
    String s1 = m.group(2);   // contains "0"
    String s2 = m.group(3);   // contains "2"
    System.out.println("s0 + "." + s1 + "." + s2);
}

這個稍微更簡單的模式也可以工作:

Pattern p = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}).*");

真正的正則表達式教程在這里

暫無
暫無

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

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