正则表达式匹配文件夹和所有子文件夹

时间:2016-01-09 09:28:51

标签: regex

我需要为备份排除过滤器编写一个Regex来排除文件夹及其所有子文件夹。

我需要匹配以下

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

我想出了这个与文件夹统计信息匹配的正则表达式,但不是统计文件夹的子文件夹。

[^/]+/statistics/

如何展开此表达式以匹配统计信息文件夹下的所有子文件夹?

2 个答案:

答案 0 :(得分:9)

使用以下正则表达式:

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

Demo on regex101

说明:

/
  ^           # 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

答案 1 :(得分:0)

使用| (或):

'.*/statistics($|/.*)'

说明:

.*             # any length string
/statistics    # statistics directory
($|/.*)        # end of string or any string starting with /

它可以完成工作,并且不难理解。经过python re模块测试。