在不在引号内时按空格分割

4
我尝试了这个:
 +|(?!(\"[^"]*\"))

但它没有起作用。 我还能做些什么让它起作用吗? 顺便提一下,我正在使用Java的string.split()。


我在这里回答了(几乎)相同的问题:https://dev59.com/WHA75IYBdhLWcg3ws7ci 那是针对C#的,但解决方案应该适用于Java。 - Jens
3个回答

17

试试这个:

[ ]+(?=([^"]*"[^"]*")*[^"]*$)

该功能将仅在空格后面跟随零个或偶数个引号(一直到字符串的结尾)时才拆分。

以下演示:

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);
        }
    }
}

将产生以下输出:

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

0

这是你要找的吗?

input.split("(?<!\") (?!\")")

我猜楼主也想知道像这样带引号的空格:"text more text"(其中有两个空格) - Bart Kiers
它不起作用,我想要的输出是:"hi there "hi there"" -> ["hi","there","hi there"] - TheBreadCat

0

这个可以工作吗?

var str="Hi there"
var splitOutput=str.split(" ");

//splitOutput[0]=Hi
//splitOutput[1]=there

抱歉,我误解了你的问题 从 Bart 的解释中添加这个 \s(?=([^"]*"[^"]*")*[^"]*$) 或者 [ ]+(?=([^"]*"[^"]*")*[^"]*$)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接