您可以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