我如何从java中的字符串中提取IP

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,但是我没有链接。

meihaoyong 回答:我如何从java中的字符串中提取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必须是有效的,这样才能正常工作...

输出就是

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 ) );
}
本文链接:https://www.f2er.com/3152314.html

大家都在问