[英]Regex to compare URLs with a wildcard that alternates ( http://example.com/user/*/profile )
I have a user specified URL that has a wildcard in it, eg http://example.com/project/*/account
我有一个用户指定的URL,其中包含通配符,例如
http://example.com/project/*/account
In this case * could be anything, a number, a character or anything else. 在这种情况下,*可以是任何东西,数字,字符或其他任何东西。
I want to get regex that would find a match for that. 我想获得可以找到匹配项的正则表达式。 The location of the wildcard * changes and could be
http://example.com/user/*/title
or http://example.com/user/*/*/*/delete
(just as an example, depends on the site ... so all possibilities should be supported) 通配符*的位置已更改,可能是
http://example.com/user/*/title
或http://example.com/user/*/*/*/delete
(仅作为示例,取决于网站...因此应支持所有可能性)
Any ideas or suggestions on how to do this? 有关如何执行此操作的任何想法或建议? I was thinking of just getting the regex code for any character and replacing all occurrence of * with that regex code.
我正在考虑只获取任何字符的正则表达式代码,并用该正则表达式代码替换所有出现的*。 Then comparing that with the current URL to see if it is a match.
然后将其与当前URL进行比较以查看是否匹配。
I think your idea should work. 我认为您的想法应该可行。
It is the same way globs are implemented in the Python standard library. 这与在Python标准库中实现glob的方式相同。 The glob is translated into an equivalent regular expression with the
*
and ?
glob使用
*
和?
转换为等效的正则表达式?
wildcards translated into .*
and .
通配符转换为
.*
和.
. 。 In your case you would replace
*
with something like [^/]+
. 在您的情况下,您可以将
*
替换为[^/]+
。
The only problem with this approach is that you'd have to escape all the regex control characters so .
这种方法的唯一问题是,您必须如此转义所有正则表达式控制字符
.
needs to be replaced with \\.
需要替换为
\\.
and [
with \\[
and so on. 和
[
与\\[
等。
You can use a URITemplate to do that matching. 您可以使用URITemplate进行匹配。
Instead of this 代替这个
http://example.com/user/*/title
You have to do this 你必须这样做
http://example.com/user/{userId}/title
You should be able to find a C# version of it or be able to build it yourself, refering the java code 您应该能够找到它的C#版本或能够自己构建它,并参考Java代码
Here's a link to java source 这是指向Java 源代码的链接
But if you are looking to match the * instead of using the URI template, replace all the occurances of '*'
with '(.*)'
and create a regexp with that newly replaced URI. 但是,如果要匹配*而不是使用URI模板,则将所有出现的
'*'
替换为'(.*)'
并使用新替换的URI创建一个正则表达式。 Then just do a regexp test
or match
然后只需进行正则表达式
test
或match
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.