Regexp javascript - url与localhost匹配 [英] Regexp javascript - url match with localhost
问题描述
我试图为网址验证找到简单正则表达式,但在regexing方面不是很好..
I trying to find a simple regexp for url validation, but not very good in regexing..
目前我有这样的正则表达式: (/ ^ https?:\ / \ / \ w /)。test(url)
Currently I have such regexp: (/^https?:\/\/\w/).test(url)
所以它允许将URL验证为 http:// localhost:8080
等。
So it's allowing to validate urls as http://localhost:8080
etc.
我想要做的是不来验证网址,如果它们最后有一些长特殊字符,例如: http:// dodo .......
或 http:// dododo&&&&&
What I want to do is NOT to validate urls if they have some long special characters at the end like: http://dodo.......
or http://dododo&&&&&
你能帮助我吗?
推荐答案
这个怎么样?
/^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?(\/[.\w]*)*$/
将匹配: http:// domain .com:port / path
或只是 http:// domain
或 http:// domain:port
/^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?$/
匹配没有路径的网址
正则表达式块的一些解释:
Some explanations of regex blocks:
域名: \ w +( \。\w +)*
将文字与点匹配: localhost
或 www.yahoo.com
(可能只要路径或端口部分开始)
Domain: \w+(\.\w+)*
to match text with dots: localhost
or www.yahoo.com
(could be as long as Path or Port section begins)
端口: (:[0-9] +)?
匹配或不匹配以分号开头的数字::8000
(它可能只有一个)
Port: (:[0-9]+)?
to match or to not match a number starting with semicolon: :8000
(and it could be only one)
路径: \ /?(\ / [。\w] *)*
匹配任何带有斜线和点的字母: /user/images/0001.jpg
(直到最后该行
Path: \/?(\/[.\w]*)*
to match any alphanums with slashes and dots: /user/images/0001.jpg
(until the end of the line)
(路径是非常有趣的部分,现在我这样做是为了允许单个或相邻的点,即这样的表达式是可能的: /。
或 /./
或 /.../
等等。如果你' d喜欢路径中的点,如域部分 - 没有边框或相邻点,然后使用 \ /?(\ / \ w +(。\ w +)*)*
regexp,类似于域部分。)
(path is very interesting part, now I did it to allow lone or adjacent dots, i.e. such expressions could be possible: /.
or /./
or /.../
and etc. If you'd like to have dots in path like in domain section - without border or adjacent dots, then use \/?(\/\w+(.\w+)*)*
regexp, similar to domain part.)
*更新*
此外,如果您希望(有效) -
字符在您的URL(或任何其他)中,您应该只为URL文本匹配扩展字符类,即 \w +
应该变为 [\-\w] +
依此类推。
Also, if you would like to have (it is valid) -
characters in your URL (or any other), you should simply expand character class for "URL text matching", i.e. \w+
should become [\-\w]+
and so on.
这篇关于Regexp javascript - url与localhost匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!