首页 > 解决方案 > 用于捕获两个双引号中的文本的正则表达式

问题描述

我正在尝试获得一个正则表达式,它将找到text1text2进入以下示例:

,"blabla "test1" blabla", "another text"

,"blabla "test2" blabla", "another text"

总而言之,我想要双引号之间的所有文本,以及双引号和逗号之间的文本。

标签: regexregex-lookaroundsregex-group

解决方案


这个表达式可能会这样做:

 ".+?"(.+?)".+?"

我们想要的输出在这个捕获组中:

 (.+?)

演示

const regex = /".+?"(.+?)".+?"/gm;
const str = `,"blabla "test1" blabla", "another text"
,"blabla "test2" blabla", "another text"`;
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}`);
    });
}


推荐阅读