简体   繁体   English

IP地址/主机名匹配正则表达式

[英]IP Address/Hostname match regex

I need to match two ipaddress/hostname with a regular expression : Like 20.20.20.20 我需要用正则表达式匹配两个ipaddress / hostname:如20.20.20.20

should match with      20.20.20.20
should match with      [http://20.20.20.20/abcd]
should not match with  20.20.20.200
should not match with  [http://20.20.20.200/abcd]
should not match with  [http://120.20.20.20/abcd]
should match with      AB_20.20.20.20
should match with      20.20.20.20_AB

At present i am using something like this regular expression: "(.*[^(\\w)]|^)20.20.20.20([^(\\w)].*|$)" But it is not working for the last two cases. 目前,我正在使用类似此正则表达式的内容: "(.*[^(\\w)]|^)20.20.20.20([^(\\w)].*|$)"但是最后它不起作用两种情况。 As the "\\w" is equal to [a-zA-Z0-9_]. 因为“ \\ w”等于[a-zA-Z0-9_]。 Here I also want to eliminate the "_" underscore. 在这里,我也想消除下划线“ _” I tried different combination but not able to succeed. 我尝试了不同的组合,但未能成功。 Please help me with this regular expression. 请用这个正则表达式帮助我。

(.*[_]|[^(\w)]|^)10.10.10.10([_]|[^(\w)].*|$)

我花了更多时间在这个上,这个正则表达式似乎起作用了。

I don't know which language you're using, but with Perl-like regular expressions you could use the following, shorter expression: 我不知道您使用的是哪种语言,但是使用类似Perl的正则表达式,您可以使用以下较短的表达式:

(?:\b|\D)20\.20\.20\.20(?:\b|\D)

This effectively says: 这实际上表示:

  1. Match word boundary ( \\b , here: the start of the word) or a non-digit ( \\D ). 匹配单词边界( \\b ,这里:单词的开头)或非数字( \\D )。
  2. Match IP address. 匹配IP地址。
  3. Match word boundary ( \\b , here: the end of the word) or a non-digit ( \\D ). 匹配单词边界( \\b ,这里:单词的末尾)或非数字( \\D )。

Note 1: ?: causes the grouping (\\b|\\D) not to create a backreference, ie to store what it has found. 注1: ?:使分组(\\b|\\D)不创建后向引用,即存储找到的内容。 You probably don't need the word boundaries/non-digits to be stored. 您可能不需要存储边界/非数字一词。 If you actually need them stored, just remove the two ?: s. 如果您确实需要存储它们,只需删除两个?:

Note 2: This might be nit-picking, but you need to escape the dots in the IP address part of the regular expression, otherwise you'd also match any other character at those positions. 注意2:这可能是挑剔的,但是您需要对正则表达式的IP地址部分中的点进行转义,否则,您还要在这些位置匹配任何其他字符。 Using 20.20.20.20 instead of 20\\.20\\.20\\.20 , you might for example match a line carrying a timestamp when you're searching through a log file... 例如,使用20.20.20.20而不是20\\.20\\.20\\.20 ,您可以在搜索日志文件时匹配带有时间戳的行...

2012-07-18 20:20:20,20  INFO  Application startup successful, IP=20.20.20.200

...even though you're looking for IP addresses and that particular one ( 20.20.20.200 ) explicitly shouldn't match, according to your question. ...根据您的问题,即使您正在寻找IP地址,并且该特定地址( 20.20.20.200 )也不应该明确匹配。 Admittedly though, this example is quite an edge case. 诚然,这个例子是一个极端的例子。

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

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