Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Regex for decimal numbers in Java?

I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.

like image 430
Gian Alix Avatar asked Mar 29 '17 04:03

Gian Alix


1 Answers

Update

To match non negative decimal number you need this regex:

^\d*\.\d+|\d+\.\d*$

or in java syntax : "^\\d*\\.\\d+|\\d+\\.\\d*$"

String regex = "^\\d*\\.\\d+|\\d+\\.\\d*$"
String string = "123.43253";

if(string.matches(regex))
    System.out.println("true");
else
    System.out.println("false");

Explanation for your original regex attempts:

[0-9]*\.?[0-9]*

with java escape it becomes :

"[0-9]*\\.?[0-9]*";

if you need to make the dot as mandatory you remove the ? mark:

[0-9]*\.[0-9]*  

but this will accept just a dot without any number as well... So, if you want the validation to consider number as mandatory you use + ( which means one or more) instead of *(which means zero or more). That case it becomes:

[0-9]+\.[0-9]+
like image 136
Rizwan M.Tuman Avatar answered Sep 22 '22 02:09

Rizwan M.Tuman