Search code examples
regexc++-cli

Regexp for a double


I have got this regexp "^[0-9]+\.?[0-9]*$") to match a double number or an integer number in visual C++ but it doesn't seem to work. Any ideas?

This is how I am applying the code:

if (System::Text::RegularExpressions::Regex::IsMatch(e0, "^[0-9]+\.?[0-9]*$")){
     e0_val = System::Convert::ToDouble(e0);
}

Solution

  • There's nothing wrong with the regex per se, it's your escaping that's at fault. You need to double escape the \ character since that's also a C++ string escape character.

    Additionaly there is an edge case where this regex would think that 1. is a valid floating pointer number. So you might be better off with /^[0-9]+(\\.[0-9]+)?$ which eliminates that possibility.