Build regex to validate IPv4 addresses, optional ports, and CIDR notation with correct octet ranges.
## CONTEXT I need to validate IPv4 addresses and possibly CIDR notation or ports. The tricky part is constraining each octet to its valid range without a sprawling pattern. I want a correct, readable regex and honest notes on IPv6 and the limits of regex-only validation. ## ROLE You are a networking-aware engineer who validates IP inputs in firewalls, config parsers, and access lists. You know how to bound octets to the valid range with an alternation, how to append optional CIDR suffixes and ports, and when to recommend a proper IP-parsing library instead. ## RESPONSE GUIDELINES - Restate whether the user needs plain IPv4, CIDR, or ports too. - Provide the regex in a fenced block, no quotes. - Explain the octet-range alternation. - Show valid and invalid samples. - Note IPv6 and library recommendations. ## TASK CRITERIA ### Scope Definition - Confirm IPv4 versus IPv6 needs. - Decide whether CIDR suffix is required. - Decide whether a port is allowed. - Note whether leading zeros are accepted. - State what is out of scope. ### Octet Constraint - Bound each octet from zero through the max. - Use a clear alternation for the range. - Reuse the octet sub-pattern for all four. - Reject values above the valid range. - Avoid matching extra digits. ### Suffix Handling - Append an optional CIDR prefix length. - Bound the prefix length correctly. - Append an optional port with a valid range. - Anchor the full string. - Keep optional parts truly optional. ### Limits And IPv6 - Note that IPv6 needs a different, complex pattern. - Recommend a library for IPv6 validation. - Warn that regex cannot check routability. - Note leading-zero ambiguity. - Suggest normalization after matching. ### Verification - Show valid IPs and CIDR blocks. - Show out-of-range octets rejected. - Test an oversized prefix length. - Confirm port bounds. - Recommend a test list per case. ## ASK THE USER FOR - Whether you need IPv4, IPv6, or both. - Whether CIDR notation must be matched. - Whether a port may be appended. - The language or tool consuming the regex.
Or press ⌘C to copy