1

I have the following input:

192.168.1.5:5555    device
192.168.1.9:5555    offline
192.168.1.12:5555   device
192.168.1.13:5555   offline

This is the regex I'm using to match IP address and port number:

([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\:\d{0,5}

The correct match would be only when there is not tabulation and then the word "offline". So I wrote the following regex and added that to the end of the previous regex:

(?!\t*offline)

but sadly I don't get the desired output, which should be:

192.168.1.5:5555    device
192.168.1.12:5555   device
JaneLilep
  • 79
  • 1
  • 9

1 Answers1

1

You may use

(?<!\d)(?:[01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])(?:\.(?:[01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){3}(?::\d{1,5})?+(?!\d|\t*offline)

See the regex demo

Regex details

  • (?<!\d) - left-hand digit boundary (no digit immediately to the left is allowed)
  • (?:[01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])(?:\.(?:[01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){3} - an IP pattern (4 dot-separated octets)
  • (?::\d{1,5})?+ - 1 or 0 occurrence (an optional occurrence) of a : and then 1 to 5 digits (note the possessive ?+ quantifier disallowing backtracking into the pattern)
  • (?!\d|\t*offline) - no digit or 0+ tabs followed with offline string are allowed immediately to the right of the current location.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Yes, this worked, thanks! You basically added the boudaries and in the last part of the regex added a negation on digits, correct? – JaneLilep Jul 01 '20 at 16:02
  • @JaneLilep I made sure no digits can appear before (`(?<!\d)`) and after (`(?!\d)`) the pattern, and the negative lookahead check is only performed once after the optional port pattern is checked with the help of the possessive quantifier that stops backtracking into the pattern. – Wiktor Stribiżew Jul 01 '20 at 16:04
  • Why was necessary to disallow backtracking into the pattern? – JaneLilep Jul 01 '20 at 16:10
  • @JaneLilep To make the lookahead check trigger once after the optional pattern is matched. – Wiktor Stribiżew Jul 01 '20 at 17:24