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

后端 未结 8 1544
一向
一向 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:56

    If you want to -> make sure it's a number AND has only one decimal <- try this RegEx instead:

    if(mystring.matches("^[0-9]*\\.?[0-9]*$")) {
        // Do something
    }
    else {
        // Do something else
    }
    

    This RegEx states:

    1. The ^ means the string must start with this.
    2. Followed by none or more digits (The * does this).
    3. Optionally have a single decimal (The ? does this).
    4. Follow by none or more digits (The * does this).
    5. And the $ means it must end with this.

    Note that bullet point #2 is to catch someone entering ".02" for example.

    If that is not valid make the RegEx: "^[0-9]+\\.?[0-9]*$"

    • Only difference is a + sign. This will force the decimal to be preceded with a digit: 0.02

提交回复
热议问题