Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a string contains only digits and decimal points?

Tags:

java

regex

For example I want to check that my when I split my string that the first part only contains numbers and decimal points.

I have done the following

String[] s1 = {"0.12.13.14-00000001-00000", "0.12.13.14-00000002-00000"};

        String[] parts_s1 = s1.split("-");
        System.out.println(parts_s1[0]);
        if(parts_s1[0].matches("[0-9]")

But thats only checking for numbers and not decimals. How can I also check for decimals in this? For example I want to check for 0.12.13.14 that it works and something like 0.12.13.14x will not work.

like image 623
user3767481 Avatar asked Jul 18 '14 20:07

user3767481


Video Answer


2 Answers

Add the dot character in the regex as follows:

if(parts_s1[0].matches("[0-9.]*")) {     // match a string containing digits or dots

The * is to allow multiple digits/decimal points.

In case at least one digit/decimal point is required, replace * with + for one or more occurrences.

EDIT:

In case the regex needs to match (positive) decimal numbers (not just arbitrary sequences of digits and decimal points), a better pattern would be:

if(parts_s1[0].matches("\\d*\\.?\\d+")) {    // match a decimal number

Note that \\d is equivalent to [0-9].

like image 99
M A Avatar answered Oct 21 '22 01:10

M A


You can use this regex:

\\d+(\\.\\d+)*

Code:

if(parts_s1[0].matches("\\d+(\\.\\d+)*") {...}
like image 25
anubhava Avatar answered Oct 21 '22 00:10

anubhava