簡體   English   中英

我如何從 java 中的字符串中提取 ip

[英]how can i extract ip from String in java

String st = "64.242.88.10 - - [07/Mar/2004:16:06:51 -0800] "GET /twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=1.2 HTTP/1.1" 200 4523"
String ip, url;
int index = line.indexOf(" - - ");
ip = line.substring(0, index)

這將提取 ip 並且我需要將 GET 之后的鏈接提取到兩個不同的變量中,我在不使用 regx 的情況下提取 ip 但我無法獲得鏈接。

您可以通過任意數量的空格split() String並獲取結果的第一項:

public static void main(String[] args) {
    String st = "64.242.88.10 - - [07/Mar/2004:16:06:51 -0800] \"GET /twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=1.2 HTTP/1.1\" 200 4523";
    // in split, use a regular expression for an arbitrary amount of whitespaces
    String[] splitResult = st.split("\\s+");
    // take the first item from the resulting array
    String ip = splitResult[0];
    // and print it
    System.out.println(ip);
}

您的String必須是有效的,然后這將起作用......

output 只是

64.242.88.10

問題應該有所啟發,以下代碼顯示了如何使用正則表達式提取 IP 和 GET 參數。

String st = "64.242.88.10 - - [07/Mar/2004:16:06:51 -0800] \"GET /twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=1.2 HTTP/1.1\" 200 4523";
Pattern pat = Pattern.compile( "(\\d+\\.\\d+\\.\\d+\\.\\d+)(?:(?!GET).)*GET ([^ ]*)" );
Matcher mat = pat.matcher( st );
while ( mat.find() ) {
    System.out.println( "1: " + mat.group( 1 ) + "; 2: " + mat.group( 2 ) );
}

暫無
暫無

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

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