请求修改正则表达式以仅验证逗号分隔的IPv4地址及CIDR格式
Modified Regex for Comma-Separated IPv4 Addresses & CIDR Ranges
Got it, let's strip out the IPv6 parts from your original regex and refine it to only validate comma-separated IPv4 addresses (with optional CIDR suffixes). Here's the tailored version:
^(((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([1-9]|1[0-9]|2[0-8]|3[0-2]))?)(\s*,\s*)?)+$
Breakdown of the Regex:
- Single IPv4 Address:
(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])ensures each octet is a valid 0-255 number. - Optional CIDR Suffix:
(\/([1-9]|1[0-9]|2[0-8]|3[0-2]))?matches valid subnet masks (1-32, since IPv4's maximum CIDR mask is 32). - Comma Separation:
(\s*,\s*)?allows commas between entries, with optional whitespace around the comma for readability. - Full String Match: The
^and$anchors ensure the entire input is validated, so there's no room for invalid characters or extra content.
Valid Examples:
- Single IPv4:
192.168.1.1 - Single CIDR range:
10.0.0.0/24 - Multiple comma-separated entries:
192.168.1.1, 172.16.0.0/16, 127.0.0.1
Invalid Examples (won't match):
- IPv6 addresses:
2001:db8::1 - Invalid IPv4 octets:
256.0.0.1 - Invalid CIDR masks:
192.168.1.0/33 - Malformed separators:
192.168.1.1,, 10.0.0.0
内容的提问来源于stack exchange,提问作者Renu Manhas
相关产品推荐
相关产品推荐

