Amirhosain Shahsavari
Amirhosain Shahsavari

Reputation: 35

Writing a regex for matching special types of folder path

I need to write a Regular Expression to find all of folder paths except the ones that are child to specific parents. For example, consider my string contains one of the following items and I want to match the whole string if the path is not a child of folder1 and folder3:

string 1: "/folder1/subfolder_0"
string 2: "/folder1/"
string 3: "/folder1"
string 4: "/folder2/subfolder_0"
string 5: "/folder3/subfolder_0"
string 6: "/folder3"

I use the regex /^\/((?!(folder1|folder3)\/)([\w\/])+)$/ to achieve my matching. But it matches string(s) 3 and 6 too while I want to match only the 4th string. My problem is where the string ends with folder1 and folder3 following no / character. Is it possible with regex?

Upvotes: 1

Views: 503

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

Your ^/((?!(folder1|folder3)/)([\w/])+)$ regex matches "/folder1" and "/folder3" because you only fail the string match if the folder1 or folder3 are followed with /. You need to allow the end of string, replace that second / in the lookahead with (?:/|$).

You may use

/^\/(?!folder[13](?:\/|$))[\w\/]+$/

See the regex demo

Note that [\w\/]+$ might be redundant here if you need to just RegExp#test() these values.

Upvotes: 1

Related Questions