如何在字母和数字之间(或数字和字母之间)拆分字符串?

2022-08-31 16:18:06

我正在尝试找出一种在java中拆分字符串的方法,该字符串遵循如下模式:

String a = "123abc345def";

由此产生的结果应如下:

x[0] = "123";
x[1] = "abc";
x[2] = "345";
x[3] = "def";

然而,我完全不知道如何实现这一目标。请问有人可以帮助我吗?我尝试过在网上搜索类似的问题,但是在搜索中很难正确表达它。

请注意:字母和数字的数量可能会有所不同(例如,可能有一个字符串,如“1234a5bcdef”)


答案 1

您可以尝试拆分 为 ,例如:(?<=\D)(?=\d)|(?<=\d)(?=\D)

str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

它匹配数字和非数字之间的位置(以任何顺序)。

  • (?<=\D)(?=\d)- 匹配非数字 () 和数字 (\D\d)
  • (?<=\d)(?=\D)- 匹配数字和非数字之间的位置。

答案 2

怎么样:

private List<String> Parse(String str) {
    List<String> output = new ArrayList<String>();
    Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
    while (match.find()) {
        output.add(match.group());
    }
    return output;
}