I have a folder path that is structured \zfolder1\folder2\folder3\folder4 and I want to use pattern matching to extract just folder2, what is the best way to do that?
Question
Question
Patter Matching from folder path
Replies
There is probably a better regex than this one..
\\.*\\(.*)\\.*\\.*
It will work if there are always 4 folders.
If the top folder always starts with the letter z, then you could try something like this:
\\z\w*\\(\w*)
Testing on RegEx101.com, It shows matching to folder2 with any of these test strings:
\zfolder1\folder2 \zfolder1\folder2\folder3 \zfolder1\folder2\folder3\folder4 \zfolder1\folder2\folder3\folder4\folder5 \zfolder1\folder2\folder3\folder4\folder5\folder6
This is the breakout explanation that RegEx101.com gives for the different components:
-
\\ matches the character \ with index 9210 (5C16 or 1348) literally (case sensitive)
-
z matches the character z with index 12210 (7A16 or 1728) literally (case sensitive)
-
\w matches any word character (equivalent to [a-zA-Z0-9_])
-
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-
\\ matches the character \ with index 9210 (5C16 or 1348) literally (case sensitive)
-
1st Capturing Group (\w*)
-
\w matches any word character (equivalent to [a-zA-Z0-9_])
-
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-