首页 > 解决方案 > 正则表达式 - 捕获标记的模板文字

问题描述

我需要帮助构建一个正则表达式来查找 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 ? `

有任何想法吗?

标签: javascriptregexecmascript-6template-literals

解决方案


正则表达式在这里对您没有帮助,最好使用 AST 解析器解析 JS 文件,例如@babel/parser- https://babeljs.io/docs/en/next/babel-parser.html


推荐阅读