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

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

I did 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 this is only a check of numbers, not decimals. How can I also check for decimal places? For example, I want to check on 12.12.13.14 that it works, and something like 12.12.13.14x will not work.

+6
source share
3 answers

Add a period character to the regular expression as follows:

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

* - allow multiple digits / decimal points.

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

EDIT:

If a regular expression must match (positive) decimal numbers (and not just arbitrary sequences of digits and decimal points), a better example would be:

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

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

+13
source

You can use this regex:

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

Code:

 if(parts_s1[0].matches("\\d+(\\.\\d+)*") {...} 
+7
source

You can simply add a dot to the list of valid characters:

 if(parts_s1[0].matches("[.0-9]+") 

This, however, will correspond to lines that consist entirely of points or have sequences of several points.

+6
source

Source: https://habr.com/ru/post/972475/


All Articles