Michael Michael - 3 months ago 6
Java Question

Partial Matching in Java Regular Expression

I wrote the following code to match whole numbers only. However, when a decimal number like 3.4 is given it matches with the number 3. Is there any way to match the whole string and otherwise reject if a number is not whole number like 3.4?

Pattern e = Pattern.compile([0-9]+);
Matcher m = e.matcher("3.4");

Answer

Your question is very confusing, but you may want to use the following to match numbers with or without decimals

Pattern e = Pattern.compile("\\d+(?:\\.\\d+)?");