Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions match floating point number but not integer

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
like image 452
mrjasmin Avatar asked Nov 06 '12 13:11

mrjasmin


People also ask

How does floating point differ from integers?

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.

What does '$' mean in regex?

$ 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.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

Does regex match dot space?

The dot matches all characters in the string --including whitespaces.


1 Answers

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.

like image 124
Martin Ender Avatar answered Oct 17 '22 00:10

Martin Ender