Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match folder and all subfolders

Tags:

regex

I need to write a Regex for a backup exclusion filter to exclude a folder and all of it's subfolders.

I need to match the following

folder1/statistics folder1/statistics/* folder2/statistics folder2/statistics/*

I came up with this Regex which matches the folder statistics, but not the subfolders of the statistics folder.

[^/]+/statistics/

How do I expand this expression to match all subfolders below the statistics folder?

like image 736
ausip Avatar asked Jan 09 '16 09:01

ausip


1 Answers

Use following regex:

/^[^\/]+\/statistics\/?(?:[^\/]+\/?)*$/gm

Demo on regex101.

Explanation:

/
  ^           # matches start of line
 [^\/]+       # matches any character other than / one or more times
 \/statistics # matches /statistics
 \/?          # optionally matches /
 (?:          # non-capturing group
   [^\/]+     # matches any character other than / one or more times
   \/?        # optionally matches /
 )*           # zero or more times
 $            # matches end of line
/
g             # global flag - matches all
m             # multi-line flag - ^ and $ matches start and end of lines
like image 81
Michał Perłakowski Avatar answered Jan 04 '23 19:01

Michał Perłakowski