Java基于两个分隔符对字符串进行排序

标签 java regex string stringtokenizer

我有一个以下格式的字符串 A34B56A12B56

我正在尝试根据前缀将数字排序到两个数组中。 例如:

  • 数组 A:34,12
  • 数组 B:56,56

最简单的方法是什么?

我尝试使用 String Tokenizer 类,并且能够提取数字,但是无法知道前缀是什么。本质上,我只能将它们提取到一个数组中。

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

Andreas 似乎已经提供了一个很好的答案,但我想在 Java 中练习一些正则表达式,因此我编写了以下适用于任何典型字母前缀的解决方案:(注释内嵌。)

String str = "A34B56A12B56";

// pattern that captures the prefix and the suffix groups
String regexStr = "([A-z]+)([0-9]+)";
// compile the regex pattern
Pattern regexPattern = Pattern.compile(regexStr);
// create the matcher
Matcher regexMatcher = regexPattern.matcher(str);

HashMap<String, ArrayList<Long>> prefixToNumsMap = new HashMap<>();
// retrieve all matches, add to prefix bucket
while (regexMatcher.find()) {
    // get letter prefix (assuming can be more than one letter for generality)
    String prefix = regexMatcher.group(1);
    // get number
    long suffix = Long.parseLong(regexMatcher.group(2));

    // search for list in map
    ArrayList<Long> nums = prefixToNumsMap.get(prefix);
    // if prefix new, create new list with the number added, update the map
    if (nums == null) {
        nums = new ArrayList<Long>();
        nums.add(suffix);
        prefixToNumsMap.put(prefix, nums);

    } else { // otherwise add the number to the existing list
        nums.add(suffix);
    }

    System.out.println(prefixToNumsMap);
}

输出:{A=[34, 12], B=[56, 56]}

关于Java基于两个分隔符对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44234033/

相关文章:

java - OSGi kf 框架的引导类路径扩展支持

java websphere MQ

java - Android - 使用编译时未知实现的 Java 接口(interface)

java - useBean 类属性的值...无效

python - 使用正则表达式捕获文本,直到第一次出现新行

javascript - 将每 N 个空格替换为换行符

c - 如何将 NULL 添加到 C 中的字符串数组

Python 正则表达式用两个定界符之一拆分字符串

python - 如何在python中找到包含焦点词的字符串的最长匹配

regex - R索引字符串带有指示核苷酸变体的字符 block