带有端口验证的 URL 正则表达式 [英] Regex for URL with port validation

查看:87
本文介绍了带有端口验证的 URL 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证像 Web 服务器那样的 url.类似于 http://localhost:8080/xyz

I need to validate a url like those of web servers. Something like http://localhost:8080/xyz

我们如何使用正则表达式做到这一点.抱歉,刚接触正则表达式.

How do we do that using regex. Sorry, new to regex.

推荐答案

相关规范可以在 rfc 中找到3986 并包括所有可能的 url 组件的常规语法定义.但是,就您的目的而言,这些可能过于笼统.一个在 http(s) 协议下只匹配 url 的压缩表达式是

the relevant specs can be found in rfc 3986 and include regular syntax definitions for all possible url components. however, for your purposes these will probably be too general. a somewhat condensed expression matching only urls under the http(s) protocol would be

http[s]?://(([[:alpha:][:digit:]-._~!$&'\(\)*+,;=]|%([0-9A-F]{2}))+|([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]))(:[0-9]+)?(/([[:alpha:][:digit:]-._~!$&'\(\)*+,;=]|%([0-9A-F]{2}))*)+(\?([[:alpha:][:digit:]-._~!$&'\(\)*+,;=/?]|%([0-9A-F]{2}))+)?(#([[:alpha:][:digit:]-._~!$&'\(\)*+,;=/?]|%([0-9A-F]{2}))+)?

可以简化为

http[s]?://(([^/:\.[:space:]]+(\.[^/:\.[:space:]]+)*)|([0-9](\.[0-9]{3})))(:[0-9]+)?(((/[^?#[:space:]]+)(\?[^#[:space:]]+)?(\#.+)?)?

以防您对 url 组件的正确语法有信心.

in case you can be confident about the proper syntax of the url components.

请注意,您可能希望使用更严格的模式,例如用于全文搜索,并且只允许 iana 注册的顶级域.

note that you might wish more restrictive patterns e.g. for full text search and to only allow for iana-registered top-level-domains.

希望能帮到你,

最好的问候,卡斯滕

这篇关于带有端口验证的 URL 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆