如何编写满足首三位非555、首位非0/1的电话号码验证正则表达式?
Phone Number Validation Regex: Meeting Your Requirements
Got it, let's work through this step by step to build a regex that checks all your boxes. First, let's recap the rules to make sure we don't miss anything:
- No phone number can start with 0 or 1
- Only numbers starting with 555 are invalid (every other prefix—including 556—is totally fine)
- Inputs like 556 (or full numbers starting with 556) should return "Phone number valid"
The Regex You Need
Here's the regex that covers all these rules, with two variations depending on whether you need to validate full-length numbers or just the prefix:
For any length of numeric phone number (minimum 1 digit, adjust as needed for real-world use):
^(?!0|1)(?!555)\d+$
For standard 10-digit US-style phone numbers:
^(?!0|1)(?!555)\d{10}$
Let's Break Down the Regex
Each part serves a specific purpose to enforce your rules:
^: Anchors the match to the start of the string—this ensures we're checking the very first characters of the number, not somewhere in the middle(?!0|1): A negative lookahead that blocks any number starting with 0 or 1(?!555): Another negative lookahead that specifically blocks numbers where the first three characters are exactly "555"\d+: Matches one or more digits (swap this with\d{10}if you need exactly 10 digits for full phone numbers)$: Anchors the match to the end of the string—this makes sure there are no extra non-numeric characters tacked on
Example Implementation (JavaScript)
Here's a quick function to show how you'd use this regex in code, including the required message output:
function checkPhoneNumber(phoneNumber) { // Use the 10-digit regex if you need full number validation, adjust as needed const phoneRegex = /^(?!0|1)(?!555)\d{10}$/; if (phoneRegex.test(phoneNumber)) { return "Phone number valid"; } return "Phone number invalid"; } // Test cases to verify it works console.log(checkPhoneNumber("5561234567")); // ✅ "Phone number valid" console.log(checkPhoneNumber("5559876543")); // ❌ "Phone number invalid" console.log(checkPhoneNumber("0123456789")); // ❌ "Phone number invalid" console.log(checkPhoneNumber("1987654321")); // ❌ "Phone number invalid" console.log(checkPhoneNumber("2223334444")); // ✅ "Phone number valid"
Quick Notes
- If your phone numbers might include formatting (like hyphens, parentheses, or spaces), you can tweak the regex to ignore those (e.g., add
[\s()-]*where needed), but since your requirements don't mention that, we kept it focused on numeric strings. - The negative lookaheads are perfect here because they let us exclude specific bad patterns without overcomplicating the rest of the match logic.
内容的提问来源于stack exchange,提问作者Rohan Shah
相关产品推荐
相关产品推荐

