Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good regular expression for real numbers in Java?

Tags:

java

regex

What's a good regular expression for real numbers in Java?

I created the regex ([-]?[\\d]*\\.[\\d]*) and tested it against the following expected outputs:

in                  out        works?
--------------------------------------
qwerty34.34abcd     34.34       yes
qwe-34.34.34abcd    -34.34      no
+17.-9abc           17.0        yes
-.abc0              0.0         no

I have to get out exactly what the column(out). Please provide a regex that passes all of these tests.

like image 645
Vanya Avatar asked Sep 20 '25 07:09

Vanya


1 Answers

Try the following:

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

This will match real numbers, including integers, with or without a sign (and with or without a number before the decimal point).

like image 176
Ant P Avatar answered Sep 21 '25 21:09

Ant P