问题描述
我不是regex专家,并且我想做一个看起来很简单并且可以在python 2.7中使用的方法,这让我很伤脑筋:验证没有查询字符串的URL的路径(无主机名).换句话说,以/开头的字符串允许字母数字值,并且不允许除以下以外的任何其他特殊字符:/
,.
,-
I'm not a regex expert and I'm breaking my head trying to do one that seems very simple and works in python 2.7: validate the path of an URL (no hostname) without the query string. In other words, a string that starts with /, allows alphanumeric values and doesn't allow any other special chars except these: /
, .
, -
我发现了此帖子与我需要的内容非常相似,但对我来说根本不工作,我可以用例如aaa
进行测试,即使它不是以/
开头,它也会返回true.
I found this post that is very similar to what I need but for me isn't working at all, I can test with for example aaa
and it will return true even if it doesn't start with /
.
我目前正在使用的正则表达式是这样的:
The current regex that I have kinda working is this one:
[^/+a-zA-Z0-9.-]
,但不适用于不是以/
开头的路径.例如:
but it doesn't work with paths that don't start with /
. For example:
-
/aaa
->是的,没关系 -
/aaa/bbb
->是的,没关系 -
/aaa?q=x
->否,没关系 -
aaa
->是的,这不行
/aaa
-> true, this is ok/aaa/bbb
-> true, this is ok/aaa?q=x
-> false, this is okaaa
-> true, this is NOT ok
推荐答案
您定义的正则表达式是字符类.相反,请尝试:
The regex you've defined is a character class. Instead, try:
^\/[/.a-zA-Z0-9-]+$
这篇关于正则表达式:验证没有查询参数的URL路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!