An attempt with regular expression to do a foolproof validation of an IV4 or Hostname:port Number.

Example texts that can be validated for any of the following:

((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d]) | ([\\p{Alnum}+ && [.{1}-_*[\p{Alnum}+]]]){1,253}:(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3})

The IPv4 address validations are mainly to ensure that the tuples are between the range 0 to 255. Also the hostname is validated against the valid names which can be alphanumeric, starting with number, subdomains separated by a single . and - and _ allowed in between, though not at end. Port range is validated from 0 to 65535

  • \$\begingroup\$ Which regex implementation are you using? \$\endgroup\$
    – t3chb0t
    Commented Aug 1, 2018 at 10:22
  • \$\begingroup\$ Java based regex - java.util.regex \$\endgroup\$ Commented Aug 1, 2018 at 10:23
  • 2
    \$\begingroup\$ Can you explain your approach? As in, why did you go this route? Part of it makes sense, other parts are less obvious. \$\endgroup\$
    – Mast
    Commented Aug 1, 2018 at 11:13
  • \$\begingroup\$ updated with the explanation \$\endgroup\$ Commented Aug 1, 2018 at 12:32

1 Answer 1


While this appears to work, there are a few things about it that are not very clear.

Reconsider the use of regex

Rather than using a regex, for the numeric ranges in particular, it may make more sense to capture those values and check them with Java statements. It would certainly reduce the size and complexity of the regex.

Document non-obvious constraints

The current regex includes a 1,253 count, the origin of which is decidedly non-obvious. RFC 1035 and RFC 822 are both obvious candiates for an authoritative source, but this regex does not conform to either of those.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.