【问题标题】:How to extract text between quotation marks in Javascript regex [duplicate]如何在Javascript正则表达式中提取引号之间的文本[重复]
【发布时间】:2020-01-13 22:48:24
【问题描述】:

如何使用 javascript 中的正则表达式来提取引号之间的内容,但不将引号保留在结果中。

示例:My name is "Julian"

结果:我想要Julian 而不是"Julian"

感谢您的帮助。

【问题讨论】:

  • 请分享到目前为止您尝试了什么?

标签: javascript regex


【解决方案1】:

我唯一的假设是引号之间可以有任何东西,除了另一个引号:

/"([^"]*)"/

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)
}

【讨论】:

  • 转义引号?
  • @Jan 今天我不想允许的津贴。但如果我有时间......
  • @Jan 这个问题没有提到引号的内容是可以逃避的。这个答案很合适。
  • @Booboo:酷。但在 JS 中不支持:D。现在通过排除转义的反斜杠来增强。 (你能感受到来自地狱的风吗?)/"((?:[^"]|(?&lt;=(\\\\)*\\)")*)"/。然后当然是替换:D
  • @BooBoo:应该这样做:"((?:[^"\\]|\\\\|\\[^\\])*)"regex101.com/r/mP4TNi/3
【解决方案2】:

你可以试试这个模式:"(\w+)"

console.log('My name is "Julian"'.match(/"(\w+)"/)[1]);

【讨论】:

  • 这会遗漏标点、转义字符和所有其他字符。
【解决方案3】:

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"! 呢?
  • 如果你想得到 Julian 和 Bob 然后使用惰性量词?。完整的正则表达式:\"(.*?)\" 和匹配项在索引大于 0 的组中可用。javascript.info/regexp-greedy-and-lazy
  • 我认为@Toto 的意思是你的regex 会在他的情况下返回Julian", not "Bob,我认为这不是OP 想要的。
猜你喜欢
  • 2012-04-28
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多