验证 url 的路径 [英] Validate the path of an url
问题描述
我正在尝试验证没有域的 url,只有路径和参数.
I'm trying to validate an url without domain, just the path and params.
我使用的正则表达式完成了大部分工作,但它有一些我不知道如何预防的错误(我对 regexp 非常菜鸟):
The regular expression that I'm using do most of the work, but It has some errors that I dont know how to prevent (I'm pretty noob with regexp):
/^(\/([\w#!:.?+=&%@!\-\/])+)$/i
下一个示例已正确验证
/asd.jsp -> true
/asd/asd.jsp -> true
/asd/asd.jsp?bar=baz&inga=42&quux -> true
/asd/asd.jsp?bar=ba z&inga=42&quux -> false
但是这些不是正确的 ulrs,它们也给了我正确的:
But this ones arent correct ulrs and them gives me true too:
/asd/asd./jsp -> true :(
/asd/asd.jsp/ -> true :(
/asd./asd.jsp -> true :(
/asd///asd.jsp -> true :(
/asd/asd.jsp&bar=baz?inga=42?quux -> true :(
您是否建议使用函数而不是正则表达式?
Do you recommend to use a function instead of a regex?
非常感谢!
推荐答案
试试这个:
^(\\/\\w+)+\\.\\w+(\\?(\\w+=[\\w\\d]+(&\\w+=[\\w\\d]+)+)+)*$
我已经转义了特殊字符,所以你可以直接在java中使用它.顺便说一下,/asd/asd.jsp?bar=baz&inga=42&quux 不是一个有效的 URL.
I already escaped special characters, so you can directly use it in java. By the way, /asd/asd.jsp?bar=baz&inga=42&quux is not a valid URL.
未转义的正则表达式:
^(\/\w+)+\.\w+(\?(\w+=[\w\d]+(&\w+=[\w\d]+)+)+)*$
这篇关于验证 url 的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!