使用正则表达式对字符串进行分组

时间:2018-03-20 09:42:49

标签: java regex

我有这样的字符串" 7.51B,8.01B,7.02E,7.52E,8.02E, 7.01D,7.51D,8.01D,8.54E,9.04E,9.54E,10.04E,10.54E,11.04E" 。我想基于1B,2E,1D,4E使用正则表达式对此字符串进行分组。有什么帮助吗?

示例:

输入

String s1 = "7.51B, 8.01B, 7.02E, 7.52E, 8.02E, 7.01D, 7.51D, 8.01D, 8.54E, 9.04E, 9.54E, 10.04E, 10.54E, 11.04E" 

输出:

1B - 7.51B, 8.01B 
2E - 7.02E, 7.52E, 8.02E 
1D - 7.01D, 7.51D, 8.01D 
4E - 8.54E, 9.04E, 9.54E, 10.04E, 10.54E, 11.04E 

1 个答案:

答案 0 :(得分:0)

就像之前在上面的文章中提到的那样,最简单的方法是通过结束分割和过滤。例如:

public static void main(String[] args){
    String s = "7.51B, 8.01B, 7.02E, 7.52E, 8.02E, 7.01D, 7.51D, 8.01D, 8.54E, 9.04E, 9.54E, 10.04E, 10.54E, 11.04E";
    String[] keys = {"1B","2E","1D","4E"};
    Map<String, List<String>> map = new TreeMap<>();
    for(String k :keys){
        map.put(k, Arrays.stream(s.split(",")).filter(e->e.endsWith(k)).collect(Collectors.toList()));
    }
    System.out.println(map);
}