开发者

Check if url equals or is a sub-directory of?

开发者 https://www.devze.com 2023-03-22 14:51 出处:网络
I am looking for a best-practice way of doing the following in java (perhaps using apache commons, some spring utility, or maybe just plain java/regex):

I am looking for a best-practice way of doing the following in java (perhaps using apache commons, some spring utility, or maybe just plain java/regex):

I need to check if a given URL pattern equals a given string or is a sub-directory of the string:

S开发者_如何转开发tring pattern = "/myPath";

if(StringUtils.startsWithIgnoreCase(url, pattern) { // }

The above (using the commons methods) works for urls such as: "../../myPath", "../../myPath/", "../../myPath/1/2"

The problem is that it also matches: "../../myPathABC". This is not desired behavior since it is not the same directory or a sub-directory.


Try URI.relativize(URI).


If you want to use regex I'd go with a regex match all with the following regex:

/^(\.\.\/)*myPath(\/|\/.*|$)/

it returns true for:

myPath
../../myPath
../../myPath/
../myPath
myPath/

and will return false for any variant of:

myPathABC

or anything not myPath. There probably is a way to do it with a java command though, java has a library for everything, I unfortunately don't know it.

Oh, it will not work for /myPath/ but I'm not sure if you want that (you didn't state it), if you want that to match as well, add a \/? before myPath.

0

精彩评论

暂无评论...
验证码 换一张
取 消