简体   繁体   English

如何使正则表达式匹配全部或不匹配

[英]How do make regex match all or nothing

I want a RegEx to match the string that composes a valid IP, colon, and port.我希望 RegEx 匹配组成有效 IP、冒号和端口的字符串。 If the string contains a valid IP and invalid port # or vice-versa, I want it to match nothing at all.如果该字符串包含有效的 IP 和无效的端口号,反之亦然,我希望它完全不匹配。 I'm implementing this in a C# app.我正在 C# 应用程序中实现它。

To do this, I'm trying to integrate the following from How to Find or Validate an IP Address为此,我正在尝试整合如何查找或验证 IP 地址中的以下内容

(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]?)

with the following from regex for port number使用正则表达式中的以下端口号

((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))

Each of these work independently to match an IP address and port number just fine.这些中的每一个都独立工作以匹配 IP 地址和端口号就好了。

I combined them我把它们结合起来

(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]?)\:((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))

and the result is, for example:结果是,例如:

256.250.139.193:1234  // bad IP, good port. The RegEx matches "56.250.139.193:1234". Fail. I want it to match nothing
1.1.1.1:65535         // good IP, good port #. The RegEx matches "1.1.1.1:65535". Pass. This is what I want it to do
1.1.1.1:65536         // good IP, bad port, matches "1.1.1.1:". Fail. I want it to match nothing

I can't figure out how to combine them to match all or nothing.我无法弄清楚如何将它们组合起来以匹配全部或不匹配。 I tried using repetition and grouping and it either didn't change what is matched or broke the RegEx entirely我尝试使用重复和分组,它要么没有改变匹配的内容,要么完全破坏了正则表达式

Put word boundaries around the pattern.在模式周围放置单词边界。

Also, you had an error in your pattern for the port number.此外,您的端口号模式有误。 [0-5]{0,5} should be [0-5]{1,5} , otherwise it matches an empty port number. [0-5]{0,5}应该是[0-5]{1,5} ,否则匹配空端口号。

\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]?):((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{1,5})|([0-9]{1,4}))\b

DEMO演示

One reliable and readable way, using a specific Perl parser Regexp::Common :一种可靠且可读的方式,使用特定的 Perl 解析器Regexp::Common

perl -MRegexp::Common -lne '
    my ($ip, $port) = /^($RE{net}{IPv4}):(\d+)$/;
    print "$ip:$port" if defined $ip and defined $port and $port  < 65536
' file

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

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