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.
但那只是检查数字而不是小数。如何检查小数呢?例如,我要检查0。12.13。14是否有效,0。12.13。14x是否有效。
3 个解决方案
#1
14
Add the dot character in the regex as follows:
在regex中添加如下点字符:
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:
如果regex需要匹配(正的)十进制数(而不仅仅是任意的数字和小数点序列),那么更好的模式应该是:
if(parts_s1[0].matches("\\d*\\.?\\d+")) { // match a decimal number
Note that \\d
is equivalent to [0-9]
.
注意,\d等同于[0-9]。
#2
7
You can use this regex:
您可以使用这个regex:
\\d+(\\.\\d+)*
Code:
代码:
if(parts_s1[0].matches("\\d+(\\.\\d+)*") {...}
#3
6
You can simply add a dot to the list of allowed characters:
您只需在允许的字符列表中添加一个点:
if(parts_s1[0].matches("[.0-9]+")
This, however, would match strings that are composed entirely of dots, or have sequences of multiple dots.
然而,这将匹配完全由点组成的字符串,或具有多个点的序列。
#1
14
Add the dot character in the regex as follows:
在regex中添加如下点字符:
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:
如果regex需要匹配(正的)十进制数(而不仅仅是任意的数字和小数点序列),那么更好的模式应该是:
if(parts_s1[0].matches("\\d*\\.?\\d+")) { // match a decimal number
Note that \\d
is equivalent to [0-9]
.
注意,\d等同于[0-9]。
#2
7
You can use this regex:
您可以使用这个regex:
\\d+(\\.\\d+)*
Code:
代码:
if(parts_s1[0].matches("\\d+(\\.\\d+)*") {...}
#3
6
You can simply add a dot to the list of allowed characters:
您只需在允许的字符列表中添加一个点:
if(parts_s1[0].matches("[.0-9]+")
This, however, would match strings that are composed entirely of dots, or have sequences of multiple dots.
然而,这将匹配完全由点组成的字符串,或具有多个点的序列。