类似URL的正则表达式模式匹配

时间:2022-12-17 16:50:40

I need to send different Response for different urls. But the Regex that I am using is not working.

我需要为不同的URL发送不同的响应。但我正在使用的正则表达式不起作用。

The two Regex in question is

有问题的两个正则表达式是

"/v1/users/[^/]+/permissions/domain/HTTP/"    

(Eg: http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP)

and

"/v1/users/[^/]+/"    

(Eg: http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363)

I am not able to figure out how to stop the regex matching after "[^/]+/". Both the pattern return the same result. It is as if due to regex both of them are same URL's. The pattern matching happens in mountebank mocking server using a matching predicate. Any help would be appreciated. Thanks.

我无法弄清楚如何在“[^ /] + /”之后停止正则表达式匹配。两种模式都返回相同的结果。好像由于正则表达式,它们都是相同的URL。模式匹配发生在使用匹配谓词的mountebank模拟服务器中。任何帮助,将不胜感激。谢谢。

1 个解决方案

#1


2  

The regular expression "/v1/users/[^/]+/" matches both urls. You are asking it to match '/v1/users/` plus anything except '/' followed by a slash. This happens in both the longer URL and the short one, which is why it matches.

正则表达式“/ v1 / users / [^ /] + /”匹配两个URL。您要求它匹配'/ v1 / users /`以及除'/'后跟斜线的任何内容。这在较长的URL和较短的URL中都会发生,这就是它匹配的原因。

A couple options:

几个选项:

You can match the longer url and not the shorter one with:

您可以匹配较长的网址而不是较短的网址:

"/v1/users/[^/]+/.+"

This matches http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP, but not http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/

这匹配http:// localhost:4544 / v1 / users / 10feec20-afd9-46a0-a3fc-9b2f18c1d363 / permissions / domain / HTTP,但不匹配http:// localhost:4544 / v1 / users / 10feec20-afd9-46a0- a3fc-9b2f18c1d363 /

You could also match just the short one by anchoring the end:

您也可以通过锚定结尾来匹配短的:

"/v1/users/[^/]+/$"

This matches the short URL but not the long one.

这匹配短网址但不匹配长网址。

#1


2  

The regular expression "/v1/users/[^/]+/" matches both urls. You are asking it to match '/v1/users/` plus anything except '/' followed by a slash. This happens in both the longer URL and the short one, which is why it matches.

正则表达式“/ v1 / users / [^ /] + /”匹配两个URL。您要求它匹配'/ v1 / users /`以及除'/'后跟斜线的任何内容。这在较长的URL和较短的URL中都会发生,这就是它匹配的原因。

A couple options:

几个选项:

You can match the longer url and not the shorter one with:

您可以匹配较长的网址而不是较短的网址:

"/v1/users/[^/]+/.+"

This matches http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP, but not http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/

这匹配http:// localhost:4544 / v1 / users / 10feec20-afd9-46a0-a3fc-9b2f18c1d363 / permissions / domain / HTTP,但不匹配http:// localhost:4544 / v1 / users / 10feec20-afd9-46a0- a3fc-9b2f18c1d363 /

You could also match just the short one by anchoring the end:

您也可以通过锚定结尾来匹配短的:

"/v1/users/[^/]+/$"

This matches the short URL but not the long one.

这匹配短网址但不匹配长网址。