【问题标题】:First Six mobile number should not be the same [closed]前六个手机号码不应该相同[关闭]
【发布时间】:2026-01-11 00:30:01
【问题描述】:

我需要查找手机号码的前6位是否相同。

最后五个数字可能相同。

但我需要检查是否只有前 6 个数字相同

例如,如果有一个手机号码 8999999589,那么在任何时候都不应该有任何连续的 6 号码。

【问题讨论】:

  • 所以如果一个号码是+44111111234,你想被注意到吗?
  • 如果你能更具体一点。你的上下文。你的代码。那么只有 SO 社区才能为您提供帮助。
  • 你能分享你当前的代码/工作吗?同时分享有效/无效样本。

标签: javascript php regex angular


【解决方案1】:

首先,获取第一个要比较的数字:

firstNumber = mobileNumberStr[0];

然后检查以下是否为真

mobileNumberStr.substr(0, 6) === firstNumber.repeat(6)

总结

如果你想要一个单行函数:

const isNumberValid = mobileNumber => mobileNumber.substr(0, 6) === mobileNumber[0].repeat(6)

【讨论】:

  • 只是一个旁注,String.prototype.repeat 是相当新的,如果它不能在你的浏览器上运行,polyfill 将是new Array(6).join(firstNumber)
【解决方案2】:

你可以这样做:

// Your array of numbers, I supposed you want to understand if
// there are 6 numbers repeated after the international prefix
// if you want something else you can easily edit indexes
const phoneNumbers = [
    '+44111111654',
    '+44111235646',
    '+44222222456',
    '+44123456789',
];

// A first cycle where we scan all the numbers in phone numbers
for (let i = 0; i < phoneNumbers.length; i++) {
    // we split the number in single chars array
    const numbers = phoneNumbers[i].split('');
    console.log(phoneNumbers[i]);
    let counter = 1;
    // A second cycle where we compair the current index element with the previous one
    for (let j = 0; j < numbers.length; j++) {
        // if the index is between 2 and 9 (+44 ->111111<- 456)
        if (j > 2 && j < 9) {
            // if the number in current position is equal to the one
            // in previous position we increment counter
            if (numbers[j] === numbers[j-1]) {
                counter++;
            }
        }
    };
    console.log(counter);
    // if counter is equal to 6, we have an invalid number (as you specified)
    if (counter === 6) {
        console.log('NOT VALID NUMBER AT INDEX: ', i);
    }
    console.log('-------');
};

输出:

+44111111654
6
NOT VALID NUMBER AT INDEX:  0
-------
+44111235646
3
-------
+44222222456
6
NOT VALID NUMBER AT INDEX:  2
-------
+44123456789
1
-------

【讨论】:

    【解决方案3】:

    愚蠢而快速的方式,使用正则表达式:

    const falseNumber = '66666655555';
    const trueNumber = '12345655555';
    
    const isFalse = function (num) {
      const regex = new RegExp('^(' + new Array(10)
        .fill(0)
        .map((v, i) => new Array(6).join(i))
        .join('|') + ')');
      return !regex.exec(num);
    }
    
    console.log(falseNumber + ' is ' + isFalse(falseNumber));
    console.log(trueNumber + ' is ' + isFalse(trueNumber));

    你甚至可以缩短它:如果你可以替换六个相同的第一个数字,那么它是错误的。

    const falseNumber = '66666655555';
    const trueNumber = '12345655555';
    
    function isFalse(num) {
      return num.replace(/^(\d)\1{5}/, '').length !== num.length;
    }
    
    console.log(falseNumber + ' is ' + isFalse(falseNumber));
    console.log(trueNumber + ' is ' + isFalse(trueNumber));

    【讨论】:

      最近更新 更多