匹配网址的模式

时间:2021-04-07 22:35:29

I have the following pattern: www.domain.com:8051/(.*)/(.*)

我有以下模式:www.domain.com:8051/(.*)/(.*)

And the following two urls:

以下两个网址:

www.domain.com:8051/first/second

www.domain.com:8051/first/second

www.domain.com:8051/first/second/third/fourth

www.domain.com:8051/first/second/third/fourth

Both urls matches. But I only want to match the first one. What must I do to exclude the "/" as a character to match?

两个网址匹配。但我只想匹配第一个。我该怎么做才能将“/”排除为匹配的字符?

Thanks, Joan.

谢谢,琼。

3 个解决方案

#1


1  

In order to exclude character you should use [^<characters to exclude>] so in your case:

为了排除字符,你应该使用[^ <字符排除> ],所以在你的情况下:

www.domain.com:8051/([^/]*)/([^/]*)

#2


1  

If those are the only patterns, why not just split on "/" and check the length?

如果这些是唯一的模式,为什么不拆分“/”并检查长度?

You still have access to the components.

您仍然可以访问组件。

#3


1  

You are using a greedy regex quantifier when you need to use the reluctant quantifier.

当您需要使用不情愿的量词时,您正在使用贪婪的正则表达式量词。

Rather than .*, use .*?. I found this cheat sheet extremely helpful when first learning how to use regular expression.

而不是。*,使用。*?。在第一次学习如何使用正则表达式时,我发现这个备忘单非常有用。

www.domain.com:8051/(.*?)/(.*?)

www.domain.com:8051/(.*?)/(.*?)

EDIT: After messing around with the pattern for a bit, I haven't been able to come up with a pattern which works, but you could check that the above pattern is found, and the following pattern is not: www.domain.com:8051/(.*?)/(.*?)/$

编辑:稍微搞乱模式后,我无法想出一个有效的模式,但你可以检查上面的模式是否找到,并且以下模式不是:www.domain.com :8051 /(.*?)/(.*?)/$

#1


1  

In order to exclude character you should use [^<characters to exclude>] so in your case:

为了排除字符,你应该使用[^ <字符排除> ],所以在你的情况下:

www.domain.com:8051/([^/]*)/([^/]*)

#2


1  

If those are the only patterns, why not just split on "/" and check the length?

如果这些是唯一的模式,为什么不拆分“/”并检查长度?

You still have access to the components.

您仍然可以访问组件。

#3


1  

You are using a greedy regex quantifier when you need to use the reluctant quantifier.

当您需要使用不情愿的量词时,您正在使用贪婪的正则表达式量词。

Rather than .*, use .*?. I found this cheat sheet extremely helpful when first learning how to use regular expression.

而不是。*,使用。*?。在第一次学习如何使用正则表达式时,我发现这个备忘单非常有用。

www.domain.com:8051/(.*?)/(.*?)

www.domain.com:8051/(.*?)/(.*?)

EDIT: After messing around with the pattern for a bit, I haven't been able to come up with a pattern which works, but you could check that the above pattern is found, and the following pattern is not: www.domain.com:8051/(.*?)/(.*?)/$

编辑:稍微搞乱模式后,我无法想出一个有效的模式,但你可以检查上面的模式是否找到,并且以下模式不是:www.domain.com :8051 /(.*?)/(.*?)/$