【发布时间】:2020-01-13 22:48:24
【问题描述】:
如何使用 javascript 中的正则表达式来提取引号之间的内容,但不将引号保留在结果中。
示例:My name is "Julian"
结果:我想要Julian 而不是"Julian"
感谢您的帮助。
【问题讨论】:
-
请分享到目前为止您尝试了什么?
标签: javascript regex
如何使用 javascript 中的正则表达式来提取引号之间的内容,但不将引号保留在结果中。
示例:My name is "Julian"
结果:我想要Julian 而不是"Julian"
感谢您的帮助。
【问题讨论】:
标签: javascript regex
我唯一的假设是引号之间可以有任何东西,除了另一个引号:
/"([^"]*)"/
console.log('My full name is "John Doe"'.match(/"([^"]*)"/)[1]);
如果要在文本中支持转义引号\",则使用以下正则表达式进行匹配:
/"((?:[^"]|(?<=\\)")*)"/
在这里,我们正在寻找不是" 或" 的任何字符,其前面是\(使用后向断言)。
但是,如果我们找到匹配项,则必须从出现的 \" 中删除 \ 字符:
let m = '"abc \\"xyz\\""'.match(/"((?:[^"]|(?<=\\)")*)"/);
if (m) {
let s = m[1].replace(/\\"/g, '"'); // remove the '\`, if any
console.log(s)
}
【讨论】:
/"((?:[^"]|(?<=(\\\\)*\\)")*)"/。然后当然是替换:D
"((?:[^"\\]|\\\\|\\[^\\])*)",regex101.com/r/mP4TNi/3
你可以试试这个模式:"(\w+)"
console.log('My name is "Julian"'.match(/"(\w+)"/)[1]);
【讨论】:
const regex = /\"(.*)\"/gm;
const str = `My name is "Julian"`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
//m.forEach((match, groupIndex) => {
// console.log(`Found match, group ${groupIndex}: ${match}`);
//});
// match without quotes are available in group with index '1'.
console.log(m[1])
}
【讨论】:
My name is "Julian", not "Bob"! 呢?
?。完整的正则表达式:\"(.*?)\" 和匹配项在索引大于 0 的组中可用。javascript.info/regexp-greedy-and-lazy
regex 会在他的情况下返回Julian", not "Bob,我认为这不是OP 想要的。