简体   繁体   中英

How do make regex match all or nothing

I want a RegEx to match the string that composes a valid IP, colon, and port. If the string contains a valid IP and invalid port # or vice-versa, I want it to match nothing at all. I'm implementing this in a C# app.

To do this, I'm trying to integrate the following from How to Find or Validate an IP Address

(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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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