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

正则表达式构建需求:仅允许开头单个+,匹配合法数字号码

Hey there! Let's fix that regex so it stops matching strings with multiple + signs and aligns with your requirements.

The Issue with Your Current Regex

Your regex ^([0|\+[0-9]{1,5})?([1-9][0-9]{7,15})$ has two main problems:

  1. Syntax mistake: The group [0|\+[0-9]{1,5} is broken. Using square brackets [0|\+] creates a character set (allowing 0, |, or +), not the "either 0 or + followed by digits" logic you intended.
  2. No guard against extra '+' signs: Even if the syntax was fixed, the regex doesn't enforce that + only appears at the start. While your second group should only match digits, it sounds like your actual regex might have a typo (like using [0-9]* instead of [1-9][0-9]{7,15}) that's letting those multi-+ strings slip through.

The Fixed Regex

To make sure + can only be at the start (if present) and all other characters are digits, here are a couple options based on your needs:

Option 1: Simple Version (Matches All Valid Examples)

If you just need to enforce one leading + (or none) plus 8+ digits:

^(?:\+?[0-9]{8,})$

Option 2: Preserve Original Prefix/Number Structure

If you want to keep the original logic (optional 1-5 digit prefix, plus an 8-16 digit local number starting with non-zero):

^(?:\+[0-9]{1,5}[1-9][0-9]{7,15}|0[0-9]{1,4}[1-9][0-9]{7,15}|[1-9][0-9]{7,15})$

How It Works

Let's break down the simple version:

  • ^ and $ anchor the match to the start/end of the string—so we check the entire string, not just a part of it.
  • \+? lets us have zero or one leading +—this ensures no extra + can appear anywhere else in the string.
  • [0-9]{8,} matches 8 or more digits (tweak the {8,} to match your minimum/maximum length needs; your examples use 9-11 digits).

Test Cases

  • ✅ Valid: +61262828282, 00123456789, 123456789 (all match the regex)
  • ❌ Invalid: +61+282827272 (contains a second +, so it gets rejected)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:04:42