Regular expression for file path which doesn't allow parent directories

邮差的信 提交于 2019-12-12 09:58:26

问题


I'm looking to write a regex for a file path that must start with some prefix. In this case it should start with '/tank/home/'. I also want to make sure that it contains no '/..' -- no jumping up to parent directories.

I spent a while fiddling around without coming up with anything quite right. I settled on using two regexes, the first which must match and the second which must not match:

'^/tank/home/'

'/\.\.(/.*)?$'

Does this do what I think it does? Is there an easier way?

This is in a bash script, for what it's worth.


回答1:


You can expand Dav's regex to include an extra trailing slash:

^(?!.*/\.\./.*)/tank/home.*$

But... a better option might be to make sure that the result of the path is something that starts under /tank/home:

FILEPATH=$(readlink -f $YOURFILE)
[[ $FILEPATH =~ ^/tank/home/ ]] && echo "starts with /tank/home/"



回答2:


You could use a negative lookahead to make sure that there aren't any /.. in the string:

^(?!.*/\.\..*)/tank/home.*$



回答3:


'^/tank/home(?!.*/\.\.(/|$))/' 

matches /tank/home/foo..bar but not /tank/home/.. or /tank/home/foo/../bar




回答4:


You could use negative lookbehind too:

/tank/home/([^/]|?(<!/..)/)+$



来源:https://stackoverflow.com/questions/1242204/regular-expression-for-file-path-which-doesnt-allow-parent-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!