Regex patterns/Validation

IPv4 address

Four numbers, each genuinely 0–255 — not the \d{1,3} version that accepts 999.

/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/
Open it in Rex

The problem

Check that a string is a dotted-quad IPv4 address with every octet in range.

How it reads

startgroupgroup25[0-5]2[0-4]\d1\d\d[1-9]skip\d\.repeatgroup25[0-5]2[0-4]\d1\d\d[1-9]skip\dend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^(?:(?:25[0-5]|2[0-4]…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. (?:(?:25[0-5]|2[0-4]\…Repeated exactly 3 times, as many as possible:
  4. (?:(?:25[0-5]|2[0-4]\…Group (not captured):
  5. (?:25[0-5]|2[0-4]\d|1…In order:
  6. (?:25[0-5]|2[0-4]\d|1…Group (not captured):
  7. 25[0-5]|2[0-4]\d|1\d\…Any one of these alternatives:
  8. 25[0-5]In order:
  9. 2The character "2"
  10. 5The character "5"
  11. [0-5]Any one of: "0" to "5"
  12. 2[0-4]\dIn order:
  13. 2The character "2"
  14. [0-4]Any one of: "0" to "4"
  15. \dA digit
  16. 1\d\dIn order:
  17. 1The character "1"
  18. \dA digit
  19. \dA digit
  20. [1-9]?\dIn order:
  21. [1-9]?Any one of: "1" to "9", optionally (zero or one time)
  22. \dA digit
  23. \.The character "."
  24. (?:25[0-5]|2[0-4]\d|1…Group (not captured):
  25. 25[0-5]|2[0-4]\d|1\d\…Any one of these alternatives:
  26. 25[0-5]In order:
  27. 2The character "2"
  28. 5The character "5"
  29. [0-5]Any one of: "0" to "5"
  30. 2[0-4]\dIn order:
  31. 2The character "2"
  32. [0-4]Any one of: "0" to "4"
  33. \dA digit
  34. 1\d\dIn order:
  35. 1The character "1"
  36. \dA digit
  37. \dA digit
  38. [1-9]?\dIn order:
  39. [1-9]?Any one of: "1" to "9", optionally (zero or one time)
  40. \dA digit
  41. $The end of the text (or of a line with the m flag)

Matches

  • 192.168.0.1
  • 255.255.255.255
  • 0.0.0.0
  • 8.8.8.8

Does not match

  • 256.1.1.1
  • 10.0.0
  • 1.2.3.4.5
  • 01.02.03.04.05

Where it bites

  • The alternatives must be ordered from most specific to least: put [1-9]?\d first and 25[0-5] never gets a chance, because the engine takes the first branch that fits.
  • It accepts leading zeros in some positions (010 reads as 10), which some parsers treat as octal.
  • IPv6 needs a completely different pattern; this one does not attempt it.

More validation patterns