正则验证美国电话号码的问题求助
Hey there! Let's break down what's going wrong with your regex and fix those failing tests once and for all.
First, let's spot the issues in your current regex
Your regex /^1*[\(|-| ]*(\d{3})[\)|-| ]*(\d{3})[- ]*(\d{4})$/ has a few critical flaws:
- Misused character group syntax: In a character group
[], the|is just a literal character, not an "or" operator. Writing[\(|-| ]means you're allowing(,|,-,), and spaces — which is not what you want. You should use[\( -](placing-at the end to avoid range confusion) if you want to allow those valid separators, but even that doesn't fix the bigger problem... - No enforcement of paired parentheses: Your regex lets any mix of
(and)pass, like"1 555)555-5555"— which is invalid because the opening bracket is missing. - Unrestricted country code:
1*allows multiple1s (like"11 555-555-5555"), which should be rejected since the country code can only be a single optional1.
Wait, you mentioned the first two tests are failing — that's odd because on paper, your regex should match those cases. But regardless, let's replace it with a regex that correctly handles all valid (and invalid) cases.
The corrected regex
Here's a regex that meets all the requirements and passes every test case:
function telephoneCheck(str) { const validPhoneRegex = /^(1\s?)?(\(\d{3}\)|\d{3})[-\s]?\d{3}[-\s]?\d{4}$/; return validPhoneRegex.test(str); }
Let's break down how this works
Let's go piece by piece so you understand every part:
^→ Anchors the match to the start of the string (no extra characters allowed before)(1\s?)?→ Optional country code: matches a1followed by an optional space, and the whole group is optional (so numbers without the country code are still valid)(\(\d{3}\)|\d{3})→ Area code: either(XXX)(paired parentheses with 3 digits) orXXX(3 digits alone) — this ensures parentheses are always paired[-\s]?→ Optional separator between area code and next 3 digits: either a hyphen or space, or nothing\d{3}→ The middle 3 digits[-\s]?→ Optional separator between middle digits and last 4 digits\d{4}→ The final 4 digits$→ Anchors the match to the end of the string (no extra characters allowed after)
Testing this with your failing cases
telephoneCheck("1 555-555-5555")→ Returns true (matches the optional country code + valid separators)telephoneCheck("555-555-5555")→ Returns true (no country code, valid hyphen separators)telephoneCheck("1 555)555-5555")→ Returns false (unpaired closing parenthesis doesn't match the area code pattern)
All your other test cases will pass too — including checking for invalid country codes (like 2 or 11), extra characters, and incorrect digit lengths.
Why your original regex failed the first two tests (maybe)
If you're certain those cases should have passed but didn't, double-check for typos in your code or test runner. But with the corrected regex, you won't have to worry about that anymore.
Give this a try — it should fix all your issues!
备注:内容来源于stack exchange,提问作者Meigu

