I have a problem to define a regexp that matches floating point numbers but do NOT identify integers.
I have the following regular expression, which matches floating numbers.
(\+|-)?([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?
How can I modify the expression above so that it doesn't match integers?
Here is a example of what should be matched:
3.3
.3
5E6
.2e-14
7E+3
4.
5.E2
1e2
Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
The dot matches all characters in the string --including whitespaces.
If your regex flavor supports lookaheads, require one of the floating-point characters before the end of the number:
((\+|-)?(?=\d*[.eE])([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?
Additional reading.
Here is also a slightly optimized version:
[+-]?(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?
We start with an optional +
or -
. Then we require one of the characters .
, e
or E
after an arbitrary amount of digits. Then we also require at least one digit, either before or after the string. The we just match digits, an optional .
and more digits. Then (completely optional) an e
or an E
and optional +
or -
and then one or more digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With