首页 > 解决方案 > Generating regex to exclude a string in path

问题描述

I'm trying to write a regex which includes all 'component.ts' files which start with 'src' but excludes those files which have 'debug' folder in its file path using

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

I'm testing the following strings on regex101 tester:

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

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

Both these strings are giving a perfect match, even though the first one has 'debug' in its path. Where am I going wrong?

标签: regex

解决方案


You are specifying a negative lookahead (?! in a character class [^((?!debug).)*$] which would then only match the characters inside the character class.

What you could do is move the negative lookahead to the beginning to assert that what follows is not /debug or /debug/:

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

Explanation

  • ^ Assert the start of the line
  • (?!.*\/debug\/) Negative lookahead to assert that what follows is not /debug/
  • src Match literally
  • \/.*component\.ts Match a forward slash followed by any character zero or more times followed by .ts
  • $ Assert the end of the string

Note that to match the dot literally you have to escape it \. or else it would match any character.


推荐阅读