正则表达式 - 捕获标记的模板文字

Regex - capture tagged template literal

我需要帮助构建一个正则表达式来查找 js 文件中所有标记的模板文字

示例:

const thing = test`
  background-color: red;
`;

正则表达式结果:

test`
  background-color: red;
`

我可以通过以下方式完成:

(test`(?:[^`])*`)

问题是我不知道如何排除内部模板文字。

例如:

const thing = test`
  background-color: ${show ? `red` : `blue`};
`;

预期的正则表达式匹配:

test`
  background-color: ${show ? `red` : `blue`};
`

实际匹配:

test`
  background-color: ${show ? `

有什么想法吗?

正则表达式在这里帮不了你,最好用像 @babel/parser - https://babeljs.io/docs/en/next/babel-parser.html

这样的 AST 解析器来解析 JS 文件