How can I find the host name and the number of requests from the same host using regex and hashmap for the below input text file:
input.txt
unicomp6.unicompt.net - - [01/JUL/1995:00:00:06 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 3985
burger.letters.com - - [01/JUL/1995:00:00:12 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 0
d104.aa.net - - [01/JUL/1995:00:00:13 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 3985
unicomp6.unicompt.net - - [01/JUL/1995:00:00:14 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 40310
d104.aa.net - - [01/JUL/1995:00:00:15 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 40310
d104.aa.net - - [01/JUL/1995:00:00:15 - 0400] "GET /images/NASA-logosmall.gif HTTP/1.0" 200 786
unicomp6.unicompt.net - - [01/JUL/1995:00:00:14 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 786
unicomp6.unicompt.net - - [01/JUL/1995:00:00:14 - 0400] "GET /shuttle/countdown/ HTTP/1.0" 200 1204
desired output:
unicomp6.unicompt.net 4
burger.letters.com 1
d104.aa.net 3
Why not using a regex ?
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\w+\\.\\w+\\.\\w+", Pattern.DOTALL);
String input = "unicomp6.unicompt.net - - [01/JUL/1995:00:00:06 - 0400]"+
"burger.letters.com - - [01/JUL/1995:00:00:12 - 0400] .... etc";
Matcher m = pattern.matcher(input);
while (m.find()) {
String s = m.group();
System.out.println(s);
}
}
you can try this (for Java 8 and beyond):
public static void main(String[] params) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("src/main/resources/input.txt"))) {
Map<String, Integer> occurrences = new HashMap<>();
lines.map( line -> line.split(" ") )
.forEach( splitted -> {
occurrences.merge(splitted[0], 1, Integer::sum);
} );
System.out.print( occurrences );
}
}
just be careful for path of your txt file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.