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

正则表达式无效问题:如何修正匹配+1(xxx)xxx-xxxx格式的正则?

Fixing Your US Phone Number Regex

Let's break down what was wrong with your original regex and fix it to properly match +1(332)313-1231:

Issues with the original regex:

  • When using the RegExp constructor, special characters like + need to be escaped with a backslash (\). Your original regex didn't escape the leading +, so it was being treated as a quantifier instead of a literal plus sign.
  • You had extra + quantifiers after ([1-9]{3}) and [1-9]{3}—these would force those sections to repeat one or more times, which doesn't align with standard US phone number formatting.
  • You didn't include matching for the parentheses () around the area code, which are present in your target string.

Corrected Regex Options

Option 1: Using RegExp Constructor (with proper escaping)

var regex = new RegExp('^\\+1\\([1-9]{3}\\)[1-9]{3}-[1-9]{4}$');

Note: We use double backslashes here because JavaScript strings escape backslashes, so \\ translates to a single \ in the final regex pattern.

Option 2: Using Regex Literal (cleaner, no extra escaping)

This is generally the preferred approach for regex in JavaScript since it avoids double-escaping headaches:

var regex = /^\+1\([1-9]{3}\)[1-9]{3}-[1-9]{4}$/;

Breakdown of the pattern:

  • ^: Anchors the match to the start of the string (ensures no extra characters before the phone number)
  • \+1: Matches the literal +1 country code
  • \(: Matches the opening parenthesis (escaped because ( is a special regex character)
  • [1-9]{3}: Matches 3 digits with no leading zero (swap to \d{3} if you want to allow leading zeros in the area code)
  • \): Matches the closing parenthesis
  • [1-9]{3}: Matches the next 3 digits (again, use \d{3} if leading zeros are permitted)
  • -: Matches the literal hyphen separator
  • [1-9]{4}: Matches the final 4 digits
  • $: Anchors the match to the end of the string (ensures no extra characters after the phone number)

Testing it out:

Running regex.test("+1(332)313-1231") will return true as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:42:22