Java String.split()拆分每个字符而不是给定正则表达式

tom*_*136 0 java regex

我有一个字符串,我想分成一个数组:

SEQUENCE? 1A?2B?3C

我尝试了以下正则表达式:

((.*\s)|([\x{2192}]*))

1. \x{2192} is the arrow mark
2. There is a space after the colon, I used that as a reference for matching the first part
Run Code Online (Sandbox Code Playgroud)

它适用于测试人员(OSX中的模式) 在此输入图像描述

但它将字符串拆分为:

[, , 1, A, , 2, B, , 3, C]

如何实现以下目标?:

[1A,2B,3C]

这是测试代码:

String str = "SEQUENCE? 1A?2B?3C"; //Note that there's an extra space after the colon
System.out.println(Arrays.toString(str.split("(.*\\s)|([\\x{2192}]*)")));
Run Code Online (Sandbox Code Playgroud)

Chr*_*ung 5

正如Richard Sitze的帖子所指出的,正则表达式的主要问题在于它应该使用+而不是*.此外,您可以对正则表达式进行进一步的改进:

  • 而不是\\x{2192},使用\u2192.因为它是一个单个字符,你不需要把它放到一个字符类([...])中,你可以直接使用它\u2192+.
  • 另外,因为|.*\\s和更松散地绑定\u2192+,你也不需要括号.所以你最后的表达很简单".*\\s|\u2192+".


Ric*_*tze 5

\u2192*将匹配0个或多个箭头-这就是为什么你的每一个字符(对空字符串分割)分割上.尝试*改为+.