正则表达式拆分数字和字母组没有空格

如果我有一个类似“11E12C108N”的字符串,它是字母组和数字组的串联,如何在它们之间没有分隔符空格字符的情况下拆分它们?

例如,我希望得到的分割是:

tokens[0] = "11" tokens[1] = "E" tokens[2] = "12" tokens[3] = "C" tokens[4] = "108" tokens[5] = "N" 

我现在有这个。

 public static void main(String[] args) { String stringToSplit = "11E12C108N"; Pattern pattern = Pattern.compile("\\d+\\D+"); Matcher matcher = pattern.matcher(stringToSplit); while (matcher.find()) { System.out.println(matcher.group()); } } 

这给了我:

 11E 12C 108N 

我可以让原始的正则表达式一次完成吗? 而不是必须再次在中间令牌上运行正则表达式?

使用以下正则表达式,并获取所有匹配项的列表。 这将是你正在寻找的。

 \d+|\D+ 

在Java中,我认为代码看起来像这样:

 Matcher matcher = Pattern.compile("\\d+|\\D+").matcher(theString); while (matcher.find()) { // append matcher.group() to your list } 

您还可以在拆分正则表达式中使用“环顾四周”

 String stringToSplit = "11E12C108N"; String[] tokens = stringToSplit .split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)"); System.out.println(Arrays.toString(tokens)); 

out [11, E, 12, C, 108, N]

想法是在数字( \d )和非数字( \D )之间分开。 换句话说,它是位置(空字符串),它具有:

  • 之前的数字(?<=\d)和之后的非数字(?=\D)
  • 之前的非数字(?<=\D)和之后的数字(?=\d)

有关(?<=..)(?=..) (以及更多)的更多信息, 请访问http://www.regular-expressions.info/lookaround.html