【问题标题】:How to create regular expression in a loop? [duplicate]如何在循环中创建正则表达式? [复制]
【发布时间】:2019-05-25 07:16:33
【问题描述】:

我目前有一个看起来像这样的正则表达式:

const ignoreRegex = new RegExp(/^\/(?!fonts|static).*$/)

但是,我也有一个动态的字符串数组,例如 "test",也需要忽略。我需要以某种方式映射这个数组并将每个字符串添加到正则表达式中,这样:

  const ignoreRegex = new RegExp(/^\/(?!fonts|static + ignoreRoutes.map(x => `|${x}`) + ).*$/)

我该怎么做?

【问题讨论】:

  • 您必须转义字符串才能正确创建正则表达式。

标签: javascript arrays node.js regex ecmascript-6


【解决方案1】:

您可以省略围绕正则表达式的/ /,并在 RegExp 构造函数中使用字符串。

请看下面的代码。

const ignoreFolders = ["fonts", "static"];
const ignoreRoutes = ["route1", "route2"];
const ignore = ignoreFolders.concat(ignoreRoutes);

const ignoreRegex = new RegExp(`^\/(?!${ignore.join("|")}).*$`);

console.log(ignoreRegex);

如果您的字符串中有任何正则表达式特殊字符,它们将被自动转义。

【讨论】:

  • 它似乎在我的开发环境中的每个字符串之前添加了一个\/。也许是因为 babel 转译?输出如下:/^\/(?!\/fonts|\/static).*$/
  • 您可能试图忽略/fonts 而不是fonts。在正则表达式中,/ 具有特殊含义。所以/ 必须使用\/ 进行转义。
  • 如果您不想要\/,请确保删除出现在ignoreRoutes 数组中的字符串之前的所有/
【解决方案2】:
const ignoreRoutes = ["fonts","static","aaa","bbb","ccc"];
const ignoreRegex = new RegExp(`^\\/(?!${ignoreRoutes.join("|")}).*$`);

【讨论】:

  • 似乎在我的开发环境中的每个字符串之前添加了一个 \/ 。也许是因为 babel 转译?输出看起来像:/^\/(?!\/fonts|\/static).*$/
  • 试试“+”。 new RegExp('^\\/(?!'+(ignoreRoutes.join("|"))+').*$');
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
相关资源
最近更新 更多