QRegularExpression For Phone Number

QRegularExpression For Phone Number

我正在尝试使用正则表达式来验证 phone 数字,但它只允许接受所有数字,而不仅仅是 10,我的正则表达式是 ^[0-9]{10},它应该只允许10 个数字 0-9。我的测试字符串是通过的 1234567890 和也通过的 703482062323。我该怎么做才能解决这个问题?

我用来测试正则表达式的代码是

QRegularExpression Phone_Num("^[0-9]{10}"); // 10 numbers in a phone number
QRegularExpressionMatch match = Phone_Num.match("12345612312312312121237890");
qDebug() << match.hasMatch();

参见 this, please. Your regex is OK as every string containing at least 10 digits will pass. You can use grouping like that: ([0-9]{10}) and then extract the group somehow (see this)。

假设你真的想要正好 10:

^[0-9]{10}$

匹配行尾,这样它就不会匹配超过 10 行的子集。

#include <QRegularExpression>
#include <QDebug>

int main() {
    QRegularExpression re("^[0-9]{10}$");
    qDebug() << re.match("12345678901123").hasMatch();
    qDebug() << re.match("1234567890").hasMatch();
    qDebug() << re.match("12345678").hasMatch();
    qDebug() << re.match("123123123a").hasMatch();
}

输出:

false
true
false
false