如何检查字符串只包含数字和小数点? [英] How to check a string contains only digits and decimal points?
问题描述
例如,我想检查一下,当我分割我的字符串时,第一部分只包含数字和小数点。
For example I want to check that my when I split my string that the first part only contains numbers and decimal points.
我已完成以下操作
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]")
但那只检查数字而不是小数。我怎么能检查这里的小数?例如我想检查0.12.13.14是否有效,0.12.13.14x之类的东西不起作用。
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.
推荐答案
在正则表达式中添加点字符,如下所示:
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.
编辑:
如果正则表达式需要匹配(正)十进制数字(不只是数字和小数点的任意序列),更好的模式是:
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
请注意 \\\\
相当于 [0-9]
。
这篇关于如何检查字符串只包含数字和小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!