How to check a string contains only digits and one occurrence of a decimal point?

后端 未结 8 1524
一向
一向 2021-02-15 14:37

My idea is something like this but I dont know the correct code

if (mystring.matches(\"[0-9.]+\")){
  //do something here
}else{
  //do something here
}
<         


        
8条回答
  •  温柔的废话
    2021-02-15 14:49

    If you want to check if a number (positive) has one dot and if you want to use regex, you must escape the dot, because the dot means "any char" :-)

    see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

    Predefined character classes
    .   Any character (may or may not match line terminators)
    \d  A digit: [0-9]
    \D  A non-digit: [^0-9]
    \s  A whitespace character: [ \t\n\x0B\f\r]
    \S  A non-whitespace character: [^\s]
    \w  A word character: [a-zA-Z_0-9]
    \W  A non-word character: [^\w]
    

    so you can use something like

    System.out.println(s.matches("[0-9]+\\.[0-9]+"));
    

    ps. this will match number such as 01.1 too. I just want to illustrate the \\.

提交回复
热议问题