Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point - Regular expression

Tags:

regex

qt

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:

  • f32
  • 32a
  • 32-
  • =33

In an answer, I am looking for:

  • An explanation of why my regular expression does not work.
  • A working version with an explanation of why it does work.

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.

like image 658
Serodis Avatar asked Nov 17 '25 06:11

Serodis


2 Answers

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.

like image 124
robbrit Avatar answered Nov 20 '25 01:11

robbrit


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

like image 21
Niet the Dark Absol Avatar answered Nov 20 '25 01:11

Niet the Dark Absol