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

求验证逗号/空格分隔6位数字字符串的正则表达式

Regex for Validating 6-Digit Groups Separated by Commas or Spaces

Got it, let's solve this input validation problem! Here's the regex pattern that perfectly fits your requirements:

^(\d{6})(?:[ ,](\d{6}))*$

Let's break down each component:

  • ^ : Anchors the match to the start of the string (no random leading characters allowed)
  • (\d{6}): Captures a single group of exactly 6 digits — this is your core valid entry
  • (?:[ ,](\d{6}))*: This non-capturing group handles additional entries with valid separators:
    • [ ,]: Matches either a single space or an English comma (the only separators you want to allow)
    • (\d{6}): Another 6-digit group that must follow the separator
    • *: Lets this separator+digit group repeat zero or more times (so you can have one entry, or multiple separated entries)
  • $: Ensures the match ends at the very end of the string (no trailing invalid characters allowed)

Example Test Cases

Passes Validation:

  • 123456 (single 6-digit number)
  • 123456,111111 (comma-separated pairs)
  • 123456 111111 (space-separated pairs)
  • 123456,111111 122335 (mixed valid separators)

Fails Validation:

  • 12345 (only 5 digits)
  • 1234567 (7 digits instead of 6)
  • 123456;111111 (uses a semicolon instead of comma/space)
  • 123456 (has a leading space)
  • 123456 (has a trailing space)
  • 12345,,111111 (double commas with no digit group in between)

Optional: Allow Whitespace Around Separators

If you want to be a bit more flexible (e.g., allow spaces before/after commas like 123456 , 111111 or leading/trailing spaces in the entire input), use this adjusted regex:

^\s*(\d{6})(?:[ ,]\s*(\d{6}))*\s*$

The \s* here matches zero or more whitespace characters, giving a bit more leniency without breaking your core rules.

内容的提问来源于stack exchange,提问作者yasir shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:20:20