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
CodePudding user response:
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
CodePudding user response:
One reliable way, using a specific Perl parser Regexp::Common:
perl -MRegexp::Common -lne 'print $& if /^$RE{net}{IPv4}:\d $/' file