Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find a float

Tags:

java

regex

I've never used regex before, but this java function requires it (shown here: How to set Edittext view allow only two numeric values and two decimal values like ##.##)

I basically just need to get a float from it the text box, should be simple. I used a tool and it said this should work:

String re1="([+-]?\\d*\\.\\d+)(?![-+0-9\\.])";

But it doesn't seem to be working, it doesn't let me put anything in the text box.

What's the right way to do this? Thanks

like image 296
Jdban101 Avatar asked May 07 '26 03:05

Jdban101


2 Answers

Try this:

String re1="^([+-]?\\d*\\.?\\d*)$";
like image 70
Paul Avatar answered May 09 '26 17:05

Paul


The right way for this problem isn't to use a regex, but just to use:

try {
     Float.parseFloat(string)
     return true;
}
catch (NumberFormatException ex) {
     return false;
}

Works perfectly fine, is the same code that is later used to parse the float and therefore bug free (or if it isn't we have a much bigger problem at hand).

like image 45
Voo Avatar answered May 09 '26 17:05

Voo