【问题标题】:How to split a String by escaping text which are in double-quotes [duplicate]如何通过转义双引号中的文本来拆分字符串[重复]
【发布时间】:2013-05-15 11:39:49
【问题描述】:

我必须拆分输入的逗号分隔字符串并将结果存储在数组中。

以下效果很好

arr=inputString.split(",")

对于这个例子

 John, Doe       =>arr[0]="John"      arr[1]="Doe" 

但它无法获得预期的输出

"John, Doe", Dan  =>arr[0]="John, Doe" arr[1]="Dan"
 John, "Doe, Dan" =>arr[0]="John"      arr[1]="Doe, Dan"

遵循正则表达式也没有帮助

        var regExpPatternForDoubleQuotes="\"([^\"]*)\"";
        arr=inputString.match(regExpPatternForDoubleQuotes);
        console.log("txt=>"+arr)

字符串可以包含两个以上的双引号。

我在上面尝试用 JavaScript。

【问题讨论】:

  • 感谢您的链接。不知道已经回答了。但是链接的答案非常冗长且很好。这里的答案是快速而简短的。我更喜欢后者。

标签: javascript regex


【解决方案1】:

这行得通:

var re = /[ ,]*"([^"]+)"|([^,]+)/g;
var match;
var str = 'John, "Doe, Dan"';
while (match = re.exec(str)) {
    console.log(match[1] || match[2]);
}

它是如何工作的:

/
    [ ,]*     # The regex first skips whitespaces and commas
    "([^"]+)" # Then tries to match a double-quoted string
    |([^,]+)  # Then a non quoted string
/g            # With the "g" flag, re.exec will start matching where it has
              # stopped last time

在这里试试:http://jsfiddle.net/Q5wvY/1/

【讨论】:

  • +1。这正是我所需要的。
【解决方案2】:

尝试将此模式与 exec 方法一起使用:

/(?:"[^"]*"|[^,]+)+/g

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 2017-02-19
    • 2016-04-19
    • 2010-11-24
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2019-01-24
    • 2013-01-06
    相关资源
    最近更新 更多