如果不在引号之间,则在空间拆分

The*_*Cat 4 java regex

我试过这个:

 +|(?!(\"[^"]*\"))
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我还能做些什么让它发挥作用?顺便说一句,我使用java的string.split().

Bar*_*ers 17

试试这个:

[ ]+(?=([^"]*"[^"]*")*[^"]*$)
Run Code Online (Sandbox Code Playgroud)

只有当这些空格后跟零或偶数个引号(一直到字符串的末尾!)时,它才会在一个或多个空格上分割.

以下演示:

public class Main {
    public static void main(String[] args) {
        String text = "a \"b c d\" e \"f g\" h";
        System.out.println("text = " + text + "\n");
        for(String t : text.split("[ ]+(?=([^\"]*\"[^\"]*\")*[^\"]*$)")) {
            System.out.println(t);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

text = a "b c d" e "f g" h

a
"b c d"
e
"f g"
h