拆分字符串而不忽略空格

Splitting a string without ignoring spaces

我正在尝试找到一种在不忽略空格的情况下拆分 Java 中的字符串的方法。 搜索后,我在 python 中找到了一种方法:

re.split(r"(\s+)", "This is the string I want to split")

会导致:

['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] 

如何在 java 中完成此操作?

是的,您需要使用环顾四周。

string.split("(?<=\s+)|(?=\s+)");
  • (?<=\s+) 匹配一个或多个空格后的边界。

  • |

  • (?=\s+) 匹配一个或多个空格之前的边界。

  • 根据匹配的边界拆分会给你想要的输出。

示例:

String s = "This is the string I want to split";
String[] parts = s.split("(?<=\s+)|(?=\s+)"); 
System.out.println(Arrays.toString(parts));

输出:

[This,  , is,  , the,  , string,  , I,  , want,  , to,  , split]