Serodis
Serodis

Reputation: 2112

Floating Point - Regular expression

I am struggling to understand this simple regular expression. I have the following attempt:

[0-9]*\.?[0-9]*

I understand this as zero-to-many numeric digits, followed by one-to-zero periods and finally ending in zero-to-many numeric digits.

I am not want to match anything other than exactly as above. I do not want positive/negative support or any other special support types. However, for some reason, the above also matches what appear to be random characters. All of the following for whatever reason match:

In an answer, I am looking for:

Edit: Due to what seems to be causing trouble, I have added the "QT" tag, that is the environment I am working with.

Edit: Due to continued confusion, I am going to add a bit of code. I am starting to think I am either misusing QT, or QT has a problem:

void subclassedQDialog::setupTxtFilters()
{
    QRegExp numbers("^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$");
    txtToFilter->setValidator(new QRegExpValidator(numbers,this));
}

This is from within a subclassed QDialog. txtToFilter is a QLineEdit. I can provide more code if someone can suggest what may be relevant. While the expression above is not the original, it is one of the ones from comments below and also fails in the same way.

Upvotes: 3

Views: 4400

Answers (4)

robbrit
robbrit

Reputation: 17960

Your problem is you haven't escaped the \ properly, you need to put \\. Otherwise the C++ compiler will strip out the \ (at least gcc does this, with a warning) and the regex engine will treat the . as any character.

Upvotes: 4

Aaron D. Marasco
Aaron D. Marasco

Reputation: 6758

One of them needs to be a + instead of *. Do you want to allow ".9" to be valid, or will you require the leading 0?

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Your expression find a match in the middle of the string. If you add anchors to the beginning and to the end of your expression, the strings from your list will be ignored. Your expression would match empty strings, but that't the price you pay for being able to match .99 and 99. strings.

^[0-9]*\.?[0-9]*$

A better choice would be

^[0-9]*(\.[0-9]+)?$

because it would match the decimal point only if at least one digit is present after it.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Put ^ at the start and $ at the end. This anchors your regex to the start and end of the string.

Upvotes: 1

Related Questions