0

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();
Root0x
  • 472
  • 1
  • 9
  • 28

2 Answers2

1

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
aep
  • 776
  • 5
  • 26
0

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

ForceBru
  • 43,482
  • 10
  • 63
  • 98