简体   繁体   中英

QRegularExpression For Phone Number

I am trying to use regular expressions to validate phone numbers but its just allowing all numbers to be accepted not just 10, my regular expression is ^[0-9]{10} which should just allow 10 numbers 0-9. my test strings were 1234567890 which passed and 703482062323 which also passed. What can i do to fix this issue?

The code im using to test the regular expression is

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

assuming you really want exactly 10:

^[0-9]{10}$

match end-of-line so that it doesn't match a subset of a line with more than 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();
}

output:

false
true
false
false

See 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM