Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training,
learning paths, books, tutorials, and more.

6.10. Floating-Point Numbers

Problem

You want to match a floating-point number and specify
whether the sign, integer, fraction and exponent parts of the number are
required, optional, or disallowed. You don’t want to use the regular
expression to restrict the numbers to a specific range, and instead
leave that to procedural code, as explained in Recipe 3.12.

Solution

Mandatory sign, integer, fraction, and exponent:

^[-+][0-9]+\.[0-9]+[eE][-+]?[0-9]+$

Regex options:
None

Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby

Mandatory sign, integer, and fraction, but no exponent:

^[-+][0-9]+\.[0-9]+$

Regex options:
None

Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby

Optional sign, mandatory integer and fraction, and no
exponent:

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

Regex options:
None

Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby

Optional sign and integer, mandatory fraction, and no
exponent:

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

Regex options:
None

Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby

Optional sign, integer, and fraction. If the integer part is
omitted, the fraction is mandatory. If the fraction is omitted, the
decimal dot must be omitted, too. No exponent.

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

Regex options:
None

Regex flavors: .NET,
Java, JavaScript, PCRE, Perl, Python, Ruby

Optional sign, integer, and fraction. If the integer part is
omitted, the fraction is mandatory. If the fraction is omitted, the
decimal dot is optional. No exponent.

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training,
learning paths, books, interactive tutorials, and more.