java - 如何从Java 7中的.txt文件提取主机名和主机请求的出现?

标签 java regex string hashmap java-io

如何使用正则表达式和哈希映射为以下输入文本文件查找主机名和来自同一主机的请求数:

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 


所需的输出:

   unicomp6.unicompt.net 4
   burger.letters.com 1
   d104.aa.net 3

最佳答案

为什么不使用正则表达式?

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);  
    }
}

关于java - 如何从Java 7中的.txt文件提取主机名和主机请求的出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60309224/

相关文章:

regex - 如何在logstash中使用mutate和gsub替换value的部分

php - 字符串中的与号导致长度/比较不正确

java - 在 Java 字符串中将 # 替换为\u0023

java - 为什么满足 "if ... <=0"标准时没有任何反应?

java - 结果集关闭后,我收到“操作不允许”消息

regex - 如何将度分秒转换为 R 中的十进制?

php - 正则表达式 - 匹配文本中的 "(posted|post|submitted) by:"

Java模糊字符串与名称匹配

java调用方法和对象

java - 在 Eclipse 服务器中运行的简单 Spring 应用程序,但未部署在 Tomcat 中