2011-05-27 101 views
1

我想写一个JavaScript正则表达式,它将匹配可能包含引号的引号中包含的匹配多行字符串。最后的报价将以逗号结尾。Javascript正则表达式可能包含引号引起的多行字符串

例如:

"some text between the quotes including " characters",

这螫与"启动时,与",结束,并且包含"字符。

我如何得到这个工作?

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

+0

乌尔正则表达式的'\”结束,$ /' – Ibu 2011-05-27 18:44:50

+0

这是不可能区分包装引号包含引号,您需要使用某种逃逸 – jwueller 2011-05-27 18:51:20

回答

1

匹配许多非",或"不跟,

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

或使用懒惰量词:

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

将这项工作多行? – alexcoco 2011-05-27 18:48:17

+1

@alex:是的,它会的,并且不管标志是什么。 – 2011-05-27 18:49:59

+0

我认为它可以被重写为'/".*?“ ,/ s' – 2011-05-27 18:50:45

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 
} 
+0

'.'将不起作用,因为引号之间可能会有换行符。 – theycallmemorty 2011-05-27 18:49:57

+0

修正了,当我以某种方式读取这个问题时,没有看到多行的东西.. – Lepidosteus 2011-05-27 18:56:13

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' 
+0

感谢您的反馈,我通常会同意,但这个正则表达式实际上是一个更大的正则表达式的一部分,它需要比解决方案更强大建议。无论如何,Upvoted :) – theycallmemorty 2011-05-27 19:53:08

相关问题