**Regex 101 Exercise I1 - Match a floating point number**

Match a floating point number.

Sample strings:

You know what a floating point number is.

**Regex 101 Exercise I1 - Match a floating point number**

Match a floating point number.

Sample strings:

You know what a floating point number is.

^d*.d+$

This of course won’t handle any thousands separators or non-English decimal separators.

I’m lazy, so I copied/pasted from existing code

_isFloatingPoint = new Regex(@"^s*[-+]?(d*(.)?)d+s*$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);

Your lack of sample strings begs a few questions.

What about exponential notation?

What about thousands separators?

What about multiple localizations? (space for thousands separators, commas for decimal points…)

What about an exponential notation?

First attempt:

^ # start of string

[+-]? # optional sign (careful w/ – in []s)

d+ # mandatory digit (if you worry about Unicode use [0-9])

(,d{3})* # optional thousands separators in groups of three digits each

(.d+)? # optional decimal point which entails mandatory trailing digits

([eE][+-]?d+)? # allow exponential notation

$ # end of string

NOTES:

Things like .5 are, by design, invalid – use 0.5 instead

Things like 5. are, by design, invalid – use 5 or 5.0 instead

I don’t like that 5,000e7 is valid. Maybe two regexps would be better

I don’t like that European numbers like 1 234,56 don’t work

Maybe a function is called for:

string RegexForFloats(

char thousands, // "," or " " or "" (to disallow)

char decimalPoint, // "." or ","

bool allowExponential // true or false

)

{

…

}

Heck, just use atof…

Regex r = new Regex("a floating point number");

Sorry, couldn’t resist.

PingBack from http://greenteafatburner.info/story.php?id=2288

PingBack from http://quickdietsite.info/story.php?id=401