用于覆盖文件路径的 JavaScript 正则表达式



我想用gulp任务替换文件路径。为此,我需要编写一个正则表达式:

我有一个文件夹结构../assets/js/components/main/main.component.html,我需要用空字符串替换整个路径../assets/js/components/**/。因此,在我的示例中应用正则表达式后,我应该只获取html文件,例如:main.component.html

正则表达式应仅匹配具有一个子文件夹级别的路径../assets/js/components/,例如:../assets/js/components/**/。仅包含../assets/js/components/的路径不应匹配,具有多个子文件夹的路径不应匹配../assets/js/components/main/shouldnotmatch/

我已经写了一个正则表达式:

^../assets/js/components/(?:[^/]+/?)*$

这里的问题是,它选择了一切。知道如何解决这个问题吗?

编辑:

更多示例:

../assets/js/components/main/ => ../assets/js/components/main/ ../assets/js/components/ => should not match ../assets/js/components/test/index.html => ../assets/js/components/test/ ../assets/js/components/main/shouldnotmatch/shouldnotmatch.html => ../assets/js/components/main/ ../assets/js/components/some_components.html => should not match ../assets/js/components/1.html => should not match

subfolder的位置使用时,您似乎希望避免匹配 HMTL/HTM 文件。

您可以使用前瞻来添加该限制并使用

^../assets/js/components/(?![^/]+.html?$)[^/]+/?

查看正则表达式演示

  • ^- 字符串的开头
  • ..- 2 点
  • /assets/js/components/- 文本字符串/assets/js/components/
  • (?![^/]+.html?$)- 紧靠当前位置的左侧,不能有:
    • [^/]+- 除/以外的 1 个或多个字符
    • .html?-.htmlhtm
    • $- 在字符串的末尾
  • [^/]+- 除/以外的 1 个或多个字符
  • /?- 1 或 0/

最新更新