生成满足多条件的10位数字手机号正则表达式(含至少3个唯一数字)
Got it, let's work through this regex problem together. You need to validate 10-digit phone numbers that meet four specific criteria, so let's break down each requirement and build the solution step by step.
The Final Regex
^(?!(\d)\1{9}$)(?!^(\d)(?:\1|(\d)){9}$)\d{10}$
Breakdown of Each Requirement & Regex Component
Let's map each of your conditions to parts of the regex:
Only contains 0-9 digits + Fixed 10-length + No spaces
The base pattern^\d{10}$handles all three of these:\dmatches any 0-9 digit (so no spaces or other non-digit characters are allowed){10}enforces exactly 10 characters^and$anchor the regex to the start and end of the string, ensuring no extra characters sneak in.
Exclude numbers with only 1 unique digit
The negative lookahead(?!(\d)\1{9}$)takes care of this:(\d)captures the first digit in the string\1{9}matches that same digit repeated 9 more times (for a total of 10 identical digits)- The lookahead ensures the string isn't this pattern (so numbers like
"1111111111"get rejected)
Exclude numbers with only 2 unique digits
The second negative lookahead(?!^(\d)(?:\1|(\d)){9}$)handles this:(\d)captures the first digit, then(?:\1|(\d))matches either that first digit or a second unique digit (captured as\2){9}repeats this group 9 times, making the total length 10- This lookahead ensures the string isn't made up of only two distinct digits (rejecting examples like
"7878787878"or"1111122222")
Test Cases
Let's verify against your examples:
- Valid matches:
"1234567890"(10 unique digits)"1122557890"(multiple unique digits)"7878787808"(3 unique digits: 7, 8, 0)
- Invalid matches:
"7878787878"(only 2 unique digits)"1111122222"(only 2 unique digits)"1111111111"(only 1 unique digit)"123456789"(only 9 digits)"123 4567890"(contains a space, fails the\d{10}check)
Notes
This regex uses standard PCRE syntax, which is supported in most programming languages (JavaScript, Python, Java, etc.). If you're working in a language with limited regex support, you might need minor adjustments, but this should work for most use cases.
内容的提问来源于stack exchange,提问作者Flexsin Tech

