如何修正VLAN输入验证正则表达式,避免重复逗号与末尾逗号
Fixed Regex for Validating VLAN IDs (1-4096) Without Duplicate/Trailing Commas
Your original regex has two critical flaws that allow invalid comma usage:
- It uses
[,]+which permits multiple consecutive commas. - The optional
?inside the repeated group lets the string end with a comma (since the VLAN ID after the comma can be omitted).
Here's the corrected regex that enforces clean comma separation (no duplicates, no trailing/leading commas) while still validating VLAN IDs in the 1-4096 range:
^(?:[1-9]\d{0,2}|[1-3]\d{3}|40(?:[0-8]\d|9[0-6]))(?:,(?:[1-9]\d{0,2}|[1-3]\d{3}|40(?:[0-8]\d|9[0-6])))*$
Key Changes Explained:
- Replaced
[,]+with a single,: This ensures only one comma separates each VLAN ID, eliminating duplicate commas entirely. - Removed the
?from the repeated group ((?:,...)*instead of(?:,...?)): Now every comma must be followed by a valid VLAN ID, so trailing commas are no longer allowed. - The pattern strictly starts and ends with a valid VLAN ID: Leading commas are automatically blocked since the string can't begin with anything other than a valid ID.
Valid Input Examples:
1(single VLAN ID)100,200,300(multiple IDs separated by single commas)4096,1,2500(mix of upper/lower range IDs)
Invalid Input Examples (Rejected by the Regex):
,123(leading comma)123,,456(duplicate commas)123,(trailing comma)0(VLAN ID below 1)4097(VLAN ID above 4096)
Content of the question originates from Stack Exchange, asked by David Hume
相关产品推荐
相关产品推荐

