Reputation: 3487
I am working in Qt 5.2.1. I need to write a regular expression that will find strings that represent numbers that have decimal values, e.g. it would find 1.234 or 123.4, but not 123 or something like a1.2. I have this regular expression:
QRegExp r("^\\d+\.\\d+$");
However I've noticed that in addition to finding values that it should, it also finds any value that is all digits and has >= 3 digits but no decimal, e.g. 12345, and values that are all digits except for one character in the middle, such as 12:345. I'm pretty sure the issue is from the regexp trying to use "." to represent any character, but I thought using "." was supposed to make it recognize the actual "." character instead. If anyone sees what I'm doing wrong, I'd appreciate the help. Thanks!
Upvotes: 0
Views: 387
Reputation: 18524
Try this:
QString txt = ui->textEdit->toPlainText();
QRegExp r("[0-9]+\\.[0-9]+");
QRegExp r("^\\d+\\.\\d+$");//with this \\. works properly too (same output)
if(txt.contains(r))
{
qDebug() << txt << "contains double" ;
}
else
qDebug() << txt << " not contains double" ;
On my computer it catches number with decimal point and ignore others.
Output:
"45:3" not contains double
"45.323" contains double
"12345" not contains double
"12:345" not contains double
Upvotes: 2