简体   繁体   English

用于匹配域名和IP地址的正则表达式

[英]Regex for matching domain and ip address

对于我的Rails应用程序,我想要一个正则表达式,它将匹配域和IP地址。

You could use something like this: 您可以使用如下形式:

\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b

Taken from here . 取自这里

EDIT: For domain names, you could use something like so: ^http://(.*?)/?.* . 编辑:对于域名,您可以使用类似这样的内容: ^http://(.*?)/?.* However, it would help if you could post some domain name examples. 但是,如果您可以发布一些域名示例,将会有所帮助。 The regex I have posted should match url which starts with http:// and it will then throw the domain name, such as google.com in a group which you can then access later. 我发布的正则表达式应该匹配以http://开头的url,然后它将把域名(例如google.com放在一个组中,您以后可以访问。

如果您使用的是网址,并尝试匹配主机部分,

/^http:\/\/([^\/])\//

Whenever I need a regex for something, I first go to the Regular Expressions Library . 每当需要正则表达式时,我都会先去正则表达式库 It is there that I found this one that looks quite reasonable: 在这里,我发现这看起来很合理:

^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$

I would use a separate regex for IP addresses and ask if the string matches either instead of trying to make both patterns fit a single matcher. 我将对IP地址使用单独的正则表达式,并询问字符串是否匹配,而不是尝试使两个模式都适合单个匹配器。

^ ^

I would say you need to be more specific, I also like to use http://www.rubular.com/ to develop my regexs. 我想说您需要更加具体,我也想使用http://www.rubular.com/开发我的正则表达式。 It has a reference key under the editor so you can play with it. 它在编辑器下有一个参考键,因此您可以使用它。 You can have fun and get your work done at the same time! 您可以玩得开心,同时完成工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM