在非转义空间分开

Mag*_*Hat 2 java regex string

我有以下形式的字符串:

/path/ /path\ with\ space/ /another/
Run Code Online (Sandbox Code Playgroud)

我需要拆分这个,所以我最终得到一个包含以下内容的数组:

[ /path/, /path with space/, /another/ ]
Run Code Online (Sandbox Code Playgroud)

有一个简单的正则表达式可以解决这个问题吗?以前我使用的是\ s +,但显然这在这里不起作用.

Mat*_*all 7

使用负面的lookbehind.

String s = "/path/ /path\\ with\\ space/ /another/";
String[] parts = s.split("(?<!\\\\)\\s+");

System.out.println(Arrays.toString(parts));
// prints [/path/, /path\ with\ space/, /another/]
Run Code Online (Sandbox Code Playgroud)

请注意,第二个元素仍然包含\s,您需要自己去掉它们.

for (int i=0; i<parts.length; i++)
{
    parts[i] = parts[i].replaceAll("\\\\ ", " ");
}

System.out.println(Arrays.toString(parts));
// prints [/path/, /path with space/, /another/]
Run Code Online (Sandbox Code Playgroud)

是的,这4点 \就是为了要匹配字符串在一个单一的一个.