zjffun blog

JS Combine Multiple RegExp

更新于 写于 JSRegExp

We can combine multiple regexps into one using source property and | (disjunction). For example, a humble regexp to get dependency:

js
const regexps = [
  /(?:(?:require|import|url)\(['"`]([^'"]+)['"`]\))/g,
  /(?:(?:\@import|from|import)\s+['"]([^'"]+)['"])/g,
  /(?:(?:url)\(([^'"]+)\))/g,
  /(?:(?:[sS][rR][cC]=)['"]([^'"]+)['"])/g,
];

const combinedRegexp = new RegExp(regexps.map((d) => d.source).join("|"), "g");

But this long complex regexp is not efficient a lot than running several smaller ones. Because those parts have different prefix.

See: