Example in Thinking in Java(the 4th E-version) Page 550:package threatAnalyzer;
import java.util.*;
import java.util.regex.*;public class ThreatAnalyzer {
static String threatData =
"58.27,82,161@02/10/2005\n" +
"204.45.234.40@02/11/2005\n" +
"58.27.82.161@02/11/2005\n" +
"58.27.82.161@02/12/2005\n" +
"58.27.82.161@02/12/2005\n" +
"[Next log section with different data format]"; /**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(threatData);
// System.out.println(threatData);
String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{2}/\\d{2}/\\d{4})";
// System.out.println(pattern);
System.out.println("scanner.hasNext(pattern) = " + scanner.hasNext(pattern));
while(scanner.hasNext(pattern)) { // the return value of hasNext is false,why???
scanner.next(pattern);
MatchResult match = scanner.match();
String ip = match.group(1);
System.out.println("ip = " + ip);
String date = match.group(2);
System.out.println("date = " + date);
System.out.format("Threat on %s from %s\n",date,ip);
}
}}why the condition expression in while is false?
Many Thanks.
import java.util.*;
import java.util.regex.*;public class ThreatAnalyzer {
static String threatData =
"58.27,82,161@02/10/2005\n" +
"204.45.234.40@02/11/2005\n" +
"58.27.82.161@02/11/2005\n" +
"58.27.82.161@02/12/2005\n" +
"58.27.82.161@02/12/2005\n" +
"[Next log section with different data format]"; /**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(threatData);
// System.out.println(threatData);
String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{2}/\\d{2}/\\d{4})";
// System.out.println(pattern);
System.out.println("scanner.hasNext(pattern) = " + scanner.hasNext(pattern));
while(scanner.hasNext(pattern)) { // the return value of hasNext is false,why???
scanner.next(pattern);
MatchResult match = scanner.match();
String ip = match.group(1);
System.out.println("ip = " + ip);
String date = match.group(2);
System.out.println("date = " + date);
System.out.format("Threat on %s from %s\n",date,ip);
}
}}why the condition expression in while is false?
Many Thanks.
//这样简单些package csdn;import java.util.*;
import java.util.regex.*; public class ThreatAnalyzer {
static String threatData =
"58.27,82,161@02/10/2005\n" +
"204.45.234.40@02/11/2005\n" +
"58.27.82.161@02/11/2005\n" +
"58.27.82.161@02/12/2005\n" +
"58.27.82.161@02/12/2005\n" +
"[Next log section with different data format]"; /**
* @param args
*/
public static void main(String[] args) { String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{2}/\\d{2}/\\d{4})";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(threatData);while(m.find()) { // the return value of hasNext is false,why??? String ip = m.group(1);
System.out.println("ip = " + ip);
String date = m.group(2);
System.out.println("date = " + date);
System.out.format("Threat on %s from %s\n",date,ip);
}
} }