【问题标题】:Splitting at space if not between quotes如果不在引号之间,则在空格处拆分
【发布时间】:2011-05-10 07:14:47
【问题描述】:

我试过这个:

 +|(?!(\"[^"]*\"))

但它没有用。 我还能做些什么来让它发挥作用? 顺便说一句,我正在使用 java 的 string.split()。

【问题讨论】:

标签: java regex


【解决方案1】:

试试这个:

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

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

以下演示:

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

产生以下输出:

文本 = a "b c d" e "f g" h 一种 “b c d” e “fg” H

【讨论】:

    【解决方案2】:

    这是你要找的吗?

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

    【讨论】:

    • 我猜 OP 还想看看引号中的空格是否像这样:"text more text"(其中有两个空格)
    • 它不起作用,我想要的输出是:"hi there \"hi there\"" -> ["hi","there","hi there"]
    【解决方案3】:

    这行得通吗?

    var str="Hi there"
    var splitOutput=str.split(" ");
    
    //splitOutput[0]=Hi
    //splitOutput[1]=there
    

    对不起,我误解了你的问题 从 Bart 的 解释中添加此内容 \s(?=([^"]*"[^"]*")*[^"]*$)[ ]+(?=([^"]*"[^"]*")*[^"]*$)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      相关资源
      最近更新 更多