How to check a string contains only digits and decimal points?

前端 未结 3 1530
一生所求
一生所求 2021-01-11 09:54

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

         


        
相关标签:
3条回答
  • 2021-01-11 10:06

    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.

    0 讨论(0)
  • 2021-01-11 10:12

    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].

    0 讨论(0)
  • 2021-01-11 10:25

    You can use this regex:

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

    Code:

    if(parts_s1[0].matches("\\d+(\\.\\d+)*") {...}
    
    0 讨论(0)
提交回复
热议问题