Regex for validating only numbers and dots

后端 未结 5 1640
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 00:20

I want a java regex expression that accepts only the numbers and dots.

for example,

             1.1.1 ----valid
             1.1   ----valid
              


        
相关标签:
5条回答
  • 2020-12-17 00:42

    I guess this is what you want:

    Pattern.compile("(([0-9](\\.[0-9]*))?){1,13}(\\.[0-9]*)?(\\.[0-9]*)?(\\.[0-9]*)?", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL | Pattern.MULTILINE);
    

    Explanation: It accepts numbers separated by dots; it starts and ends with number; a number can have multiple digits; one number without dots is not accepted.

    The output like this--

    • 1.1
    • 1.12
    • 1.1.5
    • 1.15.1.4
    0 讨论(0)
  • 2020-12-17 00:44
    <!DOCTYPE html>
    <html>
    <body>
    
    <p>RegEx to allow digits and dot</p>
    Number: <input type="text" id="fname" onkeyup="myFunction()">
    
    <script>
    function myFunction() {
        var x = document.getElementById("fname");
        x.value = x.value.replace(/[^0-9\.]/g,"");
    }
    </script>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-17 00:48

    So you want a regex that wants numbers and periods but starts and ends with a number?

    "[0-9][0-9.]*[0-9]"
    

    But this isn't going to match things like 1. which doesn't have any periods, but does start and end with a number.

    0 讨论(0)
  • 2020-12-17 00:50

    I guess this is what you want:

    ^\d+(\.\d+)*$
    

    Explanation: It accepts numbers separated by dots; it starts and ends with number; a number can have multiple digits; one number without dots is also accepted.

    Variant without multiple digits:

    ^\d(\.\d)*$
    

    Variants where at least one dot is required:

    ^\d+(\.\d+)+$
    ^\d(\.\d)+$
    

    Don't forget that in Java you have to escape the \ symbols, so the code will look like this:

    Pattern NUMBERS_WITH_DOTS = Pattern.compile("^\\d+(\\.\\d+)*$");
    
    0 讨论(0)
  • 2020-12-17 01:03
    "^\\d(\\.\\d)*$"
    
    1     ----valid (if it must be not valid, replace `*` => `+` )
    1.1.1 ----valid
    1.1   ----valid
    1.1.1.1---valid
    1.    ----not valid
    11.1.1 ---not valid (if it must be valid, add `+` after each `d`) 
    
    0 讨论(0)
提交回复
热议问题