ant路径匹配及对应正则实现

总结

ant风格的匹配就是通过独特的匹配符简化URI规则的匹配。

ant风格的匹配符

ANT通配符有三种:

通配符 说明
? 匹配任何单字符,必须要有1个
* 匹配0或者任意数量的字符
** 匹配0或者更多的目录

栗子:

/home:
f.a     fa.a    ff.a    single  sub     sxngle

./sub:
a.file

./sub/ssb:
a.file

./sub2:
a.file
URL 说明 结果
/home/*.a 匹配/home目录下所有以 .a 结尾的文件 f.a, fa.a, ff.a
/home/s?ngle 匹配/home目录下 s_ngle 的文件 single, sxngle
/**/a.file 匹配任意路径下的a.file文件 /home/sub/a.file, /home/sub/ssb/a.file, /home/sub2/a.file
/home/**/sub/a.file 匹配/home目录下的任意子目录(深度不限)为/sub的下面的a.file文件 /home/sub/a.file, /home/sub2/a.file, /home/sub/ssb/a.file
/home/*/a.file 匹配/home/目录下任意子目录(深度为1)的a.file文件 /home/sub/a.file, /home/sub2/a.file

注意:ant匹配是按照最长匹配原则匹配的
说明,URL请求/app/dir/file.jsp,现在存在两个路径匹配模式//.jsp和/app/dir/.jsp,那么会根据模式/app/dir/.jsp来匹配
因为 /app/dir/
.jsp 模式,去除匹配符,有13个字符匹配,而 /
/*.jsp 模式仅有4个字符匹配

与正则比较

对应正则

ant regex
/home/*.a \/home\/[^/]*\.a
/home/s?ngle \/home\/s[^/]{1}ngle
/**/a.file (\/.*)*\/a\.file
/home/**/sub/a.file \/home(\/.*)*\/sub\/a.file
/home/*/a.file \/home\/[^/]*\/a\.file

可以看到,使用正则达到ant风格的路径匹配不仅复杂,而且不好理解。

猜你喜欢

转载自blog.csdn.net/weixin_46080554/article/details/109718209
今日推荐