A regular expression for a file path that does not allow parent directories

I want to write a regular expression for a file path that should start with some prefix. In this case, it should start with '/ tank / home /'. I also want to make sure that it does not contain "/ .." - it does not jump to the parent directories.

I spent some time messing around without coming up with anything completely right. I decided to use two regular expressions, the first of which should match, and the second should not match:

'^/tank/home/'

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

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

This is the value of a bash script, for what it's worth

+1
source share
4 answers

Dav regex, :

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

... , , /tank/home:

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

lookahead, , /..:

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

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

+1
source

You can also use a negative lookbehind:

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

0
source

Source: https://habr.com/ru/post/1779206/


All Articles