原始字串:
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
"
-匹配报价([^"\\]*(?:\\.[^"\\]*)*)
-的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句