2017-04-18 59 views
-3

一个Java库抛出“标签”分隔值(每行)下面REGEX获得标签值和它的频率,其我使用

ID1 John 
ID2 Jerry 
ID3 John 
ID4 Mary 
ID5 John 

我试图获得names和示出单个String输出作为其频率

John 3 
Jerry 1 
Mary 1 

有没有办法实现这个使用正则表达式(字符串匹配再取频率计数)

回答

0

是有一种方法来实现这个使用正则表达式(子串匹配,然后采取 的频率计数)?

这不是100%可能,如果它不是不可能的,所以你可以创建自己的简单程序来解决这个问题。

下面是一段简单的代码就可以解决你的问题:

public static void main(String[] args) { 
    String str = "ID1 John\n" 
      + "ID2 Jerry\n" 
      + "ID3 John\n" 
      + "ID4 Mary\n" 
      + "ID5 John"; 

    //replace all the first part which contain (ID_Number_Space) 
    //And split with \n 
    String spl[] = str.replaceAll("(ID\\d+\\s)", "").split("\n"); 

    //result of this array is [John, Jerry, John, Mary, John] 

    //create a map, which contain your key (name) value (nbr occurrence) 
    Map<String, Integer> map = new HashMap<>(); 
    for (String s : spl) { 
     if (map.containsKey(s)) { 
      map.put(s, map.get(s) + 1); 
     } else { 
      map.put(s, 1); 
     } 
    } 

    //Print your array 
    for (Map.Entry entry : map.entrySet()) { 
     System.out.println(entry.getKey() + " - " + entry.getValue()); 
    } 
} 

输出

John - 3 
Jerry - 1 
Mary - 1