简体   繁体   English

检查url是否等于或是子目录?

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

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): 我正在寻找一种在java中执行以下操作的最佳实践方法(可能使用apache commons,一些spring实用程序,或者可能只是简单的java / regex):

I need to check if a given URL pattern equals a given string or is a sub-directory of the string: 我需要检查给定的URL模式是否等于给定的字符串或是否是字符串的子目录:

String pattern = "/myPath";

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

The above (using the commons methods) works for urls such as: "../../myPath" , "../../myPath/" , "../../myPath/1/2" 以上(使用公共方法)适用于以下网址: "../../myPath" "../../myPath/""../../myPath/1/2"

The problem is that it also matches: "../../myPathABC" . 问题是它也匹配: "../../myPathABC" This is not desired behavior since it is not the same directory or a sub-directory. 这不是所需的行为,因为它不是同一目录或子目录。

If you want to use regex I'd go with a regex match all with the following regex: 如果你想使用正则表达式,我会使用以下正则表达式进行正则表达式匹配:

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

it returns true for: 它返回true为:

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

and will return false for any variant of: 并且对于以下任何变体将返回false:

myPathABC

or anything not myPath . 或任何不是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. 可能有一种方法可以用java命令来做,java有一个库用于所有东西,我很遗憾不知道它。

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 \\/? \\/? ,它不适用于/myPath/但是我不确定你是否想要它(你没有说明),如果你想要匹配它,添加一个\\/? before myPath . myPath之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM