代码之家  ›  专栏  ›  技术社区  ›  Sherin Sunny

生成regex以排除路径中的字符串

  •  1
  • Sherin Sunny  · 技术社区  · 6 年前

    我正在尝试编写一个regex,其中包含所有以“src”开头的“component.ts”文件,但不包括那些在其文件路径中包含“debug”文件夹的文件,使用

    (src\/.*[^((?!debug).)*$]/*.component.ts)
    

    我正在Regex101测试仪上测试以下字符串:

    src/abcd/debug/xtz/component/ddd/xyz.component.ts
    
    src/abcd/arad/xtz/xyz.component.ts
    

    这两个字符串都提供了完美的匹配,即使第一个字符串的路径中有“debug”。我哪里出错了?

    2 回复  |  直到 6 年前
        1
  •  2
  •   The fourth bird    6 年前

    (?! character class [^((?!debug).)*$]

    /debug /debug/

    ^(?!.*\/debug\/)src\/.*component\.ts$

    • ^ 断言行首
    • (?!.*\/debug\/) /调试/
    • src
    • \/.*component\.ts .ts
    • $

    注意,要匹配点,你必须避开它。 \.

        2
  •  1
  •   Aankhen Jon    6 年前

    您的regex匹配:

    • src/
    • 后跟一个不在字符类中的字符 ((?!debug).)*$
    • 后跟非换行符
    • component
    • 后接非换行符后接 ts

    也就是说, [^((?!debug).)*$]

    • src
    • 后跟一个或多个路径段,每个路径段不等于 debug

    这给了我们:

    ^src(?:/[^/]+(?<!debug))+/[^/]+\.component\.ts$
    

    Try it on Regex101.

    我添加了 ^ $ 因为我假设您希望整个输入匹配。如果在一个大字符串中搜索,则可以删除这些字符串,而改为更改 [^/] [^\n/]