有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正则表达式获取选项卡式值及其频率

我使用的Java库将“tab”分隔的值作为(每行)单个字符串输出抛出,如下所示

ID1 John
ID2 Jerry
ID3 John
ID4 Mary
ID5 John

我正在尝试获取names及其频率

John  3
Jerry 1
Mary  1

有没有一种方法可以通过使用正则表达式(子字符串匹配然后进行频率计数)来实现这一点


共 (1) 个答案

  1. # 1 楼答案

    Is there a way to achieve this using regex (substring match then take the frequency count)?

    这不是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