You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正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:

  1. It uses [,]+ which permits multiple consecutive commas.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:02:43