匹配引号中的文本时,正则表达式不会省略引号 [英] Regex doesn't omit quotes when matching text in quotes
本文介绍了匹配引号中的文本时,正则表达式不会省略引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 node.js 中使用正则表达式对双引号内的文本进行非贪婪捕获.大多数 Google 结果都说我应该使用以下之一:
I'm trying to do a non-greedy capture of text inside double quotation marks with regex in node.js. Most of the Google results say I should use one of these:
"(.*?)"
"([^"]*)"
我都试过,但我的代码没有删除引号.我的代码看起来是这样:
I tried both, but my code doesn't remove the quotes. My code looks so:
var testStr = '|> "Song" by "Artist" on "Album" <3';
var regex = /"([^"]*)"/g; // or /"(.*?)"/g
var info = testStr.match(regex);
if (info){
console.dir(info[0]);
console.dir(info[1]);
console.dir(info[2]);
}
我的输出是这样的:
'"Song"'
'"Artist"'
'"Album"'
我做错了什么?
推荐答案
match
方法返回一个仅包含 匹配项 的数组.请参阅MDN:
match
method returns an array of just matches. See MDN:
捕获的组不会返回.
修复方法是使用 exec
:
var re = /"(.*?)"/g;
var str = '|> "Song" by "Artist" on "Album" <3';
while ((m = re.exec(str)) !== null) {
document.getElementById("res").innerHTML += m[1] + "<br />";
}
<div id="res"/>
这篇关于匹配引号中的文本时,正则表达式不会省略引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文