使用正则表达式获取子字符串(带有“”的字符串)

Getting substrings (strings with "") with Regex

我有一个这样的主字符串:

const mainString: string = `
let myStr: string = "Hello world";
function x() { }
let otherVar: number = 4;
let otherString: string = "Other string value";
// something else INSIDE the main string
`;

现在我需要格式化这个主字符串,但是子字符串会导致不需要的东西,所以我需要得到它们。

到目前为止我使用的正则表达式是:/"([^"]*)"/g。 有了它,我会得到例如['"Hello world"', '"Other string value"'](在上面的 mainString 上下文中)。

但是在这些子字符串中有一个 "\"" 会丢掉我的正则表达式并从头到 \" 给我这部分,然后,如果在其他地方使用了其他子字符串, 给我子字符串的真正结尾 " (错误地作为开始符号)直到下一个子字符串的开始...

一件重要的事情:我绝对 无法控制 之前和 "substring value" 之外的任何事情。

我的用例的正确正则表达式是什么?

试试这个

"((\"|[^"])*?)"

\" - 表示寻找 \"

| - 或

*? - 为了不贪心

参见:regex101