原始字符串:
some text "some \"string\"right here "
想要获得:
"some \"string\"right here"
我正在使用以下正则表达式:
/\"(.*?)\"/g
最佳答案
使用解析器正确解析字符串
使用 JavaScript 正则表达式,不可能从正确的双引号开始匹配。您将匹配一个转义的,或者在文字 \
之后无法匹配正确的双引号。在报价之前。因此,最安全的方法是使用解析器。这是一个示例:
var s = "some text \\\"extras\" some \\\"string \\\" right\" here \"";
console.log("Incorrect (with regex): ", s.match(/"([^"\\]*(?:\\.[^"\\]*)*)"/g));
var res = [];
var tmp = "";
var in_quotes = false;
var in_entity = false;
for (var i=0; i<s.length; i++) {
if (s[i] === '\\' && in_entity === false) {
in_entity = true;
if (in_quotes === true) {
tmp += s[i];
}
} else if (in_entity === true) { // add a match
in_entity = false;
if (in_quotes === true) {
tmp += s[i];
}
} else if (s[i] === '"' && in_quotes === false) { // start a new match
in_quotes = true;
tmp += s[i];
} else if (s[i] === '"' && in_quotes === true) { // append char to match and add to results
tmp += s[i];
res.push(tmp);
tmp = "";
in_quotes = false;
} else if (in_quotes === true) { // append a char to the match
tmp += s[i];
}
}
console.log("Correct results: ", res);
不太安全的正则表达式方法
无法使用惰性点匹配模式匹配您需要的字符串,因为它将在第一个
"
之前停止。 . 如果您知道您的字符串在带引号的子字符串之前永远不会有转义引号,并且如果您确定没有文字 \
双引号前 (并且这些条件对于安全使用正则表达式非常严格),您可以使用/"([^"\\]*(?:\\.[^"\\]*)*)"/g
见 regex demo"
- 匹配报价 ([^"\\]*(?:\\.[^"\\]*)*)
- 0个或多个序列[^"\\]*
- 0+ 非- \
和非"
小号 (?:\\.[^"\\]*)*
- 零个或多个序列\\.
- 任何转义符号[^"\\]*
- 0+ 非- \
和非"
小号 "
- 尾随报价 JS 演示:
var re = /"([^"\\]*(?:\\.[^"\\]*)*)"/g;
var str = `some text "some \\"string\\"right here " some text "another \\"string\\"right here "`;
var res = [];
while ((m = re.exec(str)) !== null) {
res.push(m[1]);
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>"; // Just for demo
console.log(res); // or another result demo
关于javascript正则表达式选择带引号的字符串但不转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563414/