Java 如何检查一个字符串只包含数字和小数点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24833364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a string contains only digits and decimal points?
提问by user3767481
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 之类的则无效。
采纳答案by M Anouti
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]
.
请注意,\\d
相当于[0-9]
.
回答by dasblinkenlight
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.
但是,这将匹配完全由点组成或具有多个点序列的字符串。
回答by anubhava
You can use this regex:
您可以使用此正则表达式:
\d+(\.\d+)*
Code:
代码:
if(parts_s1[0].matches("\d+(\.\d+)*") {...}