user3441194
user3441194

Reputation: 77

Regex to exclude substring

I want to write regex that:

  1. pass string starting with /scripts/my_app/ (/scripts/my_app/xxxx.sh or /scripts/my_app/yyyyy/xxxz.sh)
  2. exclude another strings starting with /scripts/ (/scripts/another_string/xxxx.sh or /scripts/some_string/yyyyy/xxxz.sh)
  3. pass any others strings like /xxxx/yyyy/zzzzz/qqqq.sh or /aaaa/bbbb/ccc.sh

Something like this ^[(\/scripts\/my_app\/)|(?!\/scripts\/)].* doesn't work.

Upvotes: 0

Views: 155

Answers (1)

The fourth bird
The fourth bird

Reputation: 163352

You can use

^/(?:scripts/my_app/|(?!scripts/)).*

Explanation

  • ^/ Start of string and match /
  • (?: Non capture group
    • scripts/my_app/ Match literally
    • | Or
    • (?!scripts/) Negative lookahead, assert not scripts/
  • ) Close non capture group
  • .* Match 0+ times any character

Regex demo

Another option is using a double negative lookahead

^/(?!scripts/(?!my_app/)).*

Regex demo

Upvotes: 1

Related Questions