我有以下形式的字符串:
/path/ /path\ with\ space/ /another/
Run Code Online (Sandbox Code Playgroud)
我需要拆分这个,所以我最终得到一个包含以下内容的数组:
[ /path/, /path with space/, /another/ ]
Run Code Online (Sandbox Code Playgroud)
有一个简单的正则表达式可以解决这个问题吗?以前我使用的是\ s +,但显然这在这里不起作用.
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点 \就是为了要匹配字符串在一个单一的一个.
| 归档时间: |
|
| 查看次数: |
791 次 |
| 最近记录: |