regular expression checking valid hostname port [closed]

99封情书 提交于 2021-01-27 21:40:37

问题


I've searched thru various websites and here for one that works but none do.

I need a regex that validates a game server hostname is correct format.

Example:

gost.gflclan.com:27015

And also the normal ip:port

103.18.138.27:27015

The hostname version can also have numbers in the subdomain or main part. And always has 5 numbers in port on both.

I've currently got this but it only works for the ip:port and not the hostname one.

([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{5})|([a-z].[a-z].[a-z]:[1-9]{5})

Thanks if you can help.


回答1:


updated :

try:

[^\:]+:[0-9]{5}

dynamically match both:

103.18.138.27:27015
gost.gflclan.com:27015

little explaination:

 [^\:]+ --- |> all chars till ':' 
   :
 [0-9]{5} --|> exactly 5 numbers



回答2:


There is a bit more cleaner code:

(([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})|(\w*.\w*.\w*)):[0-9]{5}



回答3:


Live demo

You forgot the + after [a-z] and the dot must be escaped:

([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{5})|([a-z]+\.[a-z]+\.[a-z]+\:[0-9]{5})


来源:https://stackoverflow.com/questions/25966391/regular-expression-checking-valid-hostname-port

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!