简体   繁体   English

如何检查字符串只包含数字和小数点?

[英]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. 例如,我想检查一下,当我分割我的字符串时,第一部分只包含数字和小数点。

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之类的东西不起作用。

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]

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. 然而,这将匹配完全由点组成的字符串,或具有多个点的序列。

You can use this regex: 你可以使用这个正则表达式:

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

Code: 码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM