📌  相关文章
📜  c++ 正则表达式验证印度电话号码模式 - C++ (1)

📅  最后修改于: 2023-12-03 14:39:55.575000             🧑  作者: Mango

C++ 正则表达式验证印度电话号码模式

在程序开发中,我们经常需要验证用户输入的电话号码是否合法。针对印度的电话号码,我们可以使用正则表达式进行验证。

正则表达式验证代码
#include <iostream>
#include <regex>

using namespace std;

bool isIndianPhoneNumber(string phoneNumber) {
    regex regexPattern("(0/91)?[7-9][0-9]{9}");

    if (regex_match(phoneNumber, regexPattern)) {
        return true;
    } else {
        return false;
    }
}

int main() {
    string phoneNumber = "8877665544";

    if (isIndianPhoneNumber(phoneNumber)) {
        cout << "This is a valid Indian phone number." << endl;
    } else {
        cout << "This is not a valid Indian phone number." << endl;
    }
}
正则表达式说明

正则表达式 (0/91)?[7-9][0-9]{9} 匹配印度的电话号码:

  • (0/91)?:表示国际区号,0 或 91,可选;
  • [7-9]:表示手机号码的第一个数字,必须是 7、8 或 9;
  • [0-9]{9}:表示剩余的 9 个数字,可以是任意数字。

因此,这个正则表达式可以匹配以下的电话号码:

  • 9876543210
  • 09876543210
  • 919876543210
测试

我们可以使用不同的电话号码进行测试:

int main() {
    string phoneNumber1 = "9876543210";
    string phoneNumber2 = "09876543210";
    string phoneNumber3 = "919876543210";
    string phoneNumber4 = "1234567890";
    string phoneNumber5 = "98765432100";

    if (isIndianPhoneNumber(phoneNumber1)) {
        cout << "This is a valid Indian phone number." << endl;
    } else {
        cout << "This is not a valid Indian phone number." << endl;
    }

    if (isIndianPhoneNumber(phoneNumber2)) {
        cout << "This is a valid Indian phone number." << endl;
    } else {
        cout << "This is not a valid Indian phone number." << endl;
    }

    if (isIndianPhoneNumber(phoneNumber3)) {
        cout << "This is a valid Indian phone number." << endl;
    } else {
        cout << "This is not a valid Indian phone number." << endl;
    }

    if (isIndianPhoneNumber(phoneNumber4)) {
        cout << "This is a valid Indian phone number." << endl;
    } else {
        cout << "This is not a valid Indian phone number." << endl;
    }

    if (isIndianPhoneNumber(phoneNumber5)) {
        cout << "This is a valid Indian phone number." << endl;
    } else {
        cout << "This is not a valid Indian phone number." << endl;
    }
}

输出:

This is a valid Indian phone number.
This is a valid Indian phone number.
This is a valid Indian phone number.
This is not a valid Indian phone number.
This is not a valid Indian phone number.

我们可以看到,第一个、第二个和第三个电话号码都符合印度的电话号码规则,而后面两个电话号码不符合。