用引号括起来的多行字符串的Javascript正则表达式,可能包含引号

时间:2011-05-27 18:43:06

标签: javascript regex

我想编写一个javascript正则表达式,它将匹配包含在引号中的多行字符串,这些字符串可能也包含引号。最终报价将以逗号结束。

例如:

"some text between the quotes including " characters",

这种刺痛以"开头,以",结尾,包含"个字符。

如何让它发挥作用?

我想真正的问题是如何匹配以"开头并以",结尾的多行字符串?

3 个答案:

答案 0 :(得分:3)

简单的match()不起作用吗?你还需要使用\ s \ S技巧使点包含换行符(实际上,这使得它接受每一个字符):

var str = "bla bla \"some text between the quotes \n including \" characters\", bla bla";
var result = str.match(/"([\s\S]+)",/);
if (result == null) {
 // no result was found
} else {
 result = result[1];
 // some text between the quotes
 // including " characters
}

答案 1 :(得分:1)

匹配许多非""后跟,

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

或使用延迟量词:

/"([\0-\uffff]*?)",/

答案 2 :(得分:1)

使用正则表达式会非常棘手,我会尝试这样的事情:

var getQuotation = function(s) {
  var i0 = s.indexOf('"')
    , i1 = s.indexOf('",');
  return (i0 && i1) ? s.slice(i0+1, i1) : undefined;
};

var s = "He said, \"this is a test of\n" +
        "the \"emergency broadcast\" system\", obviously.";
getQuotation(s); // => 'this is a test of
                 //     the "emergency broadcast" system'