Regex for numbers only

后端 未结 18 2259
野性不改
野性不改 2020-11-22 03:29

I haven\'t used regular expressions at all, so I\'m having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the

相关标签:
18条回答
  • 2020-11-22 04:03

    If you need to tolerate decimal point and thousand marker

    var regex = new Regex(@"^-?[0-9][0-9,\.]+$");
    

    You will need a "-", if the number can go negative.

    0 讨论(0)
  • 2020-11-22 04:07
     console.log(/^(0|[1-9][0-9]*)$/.test(3000)) // true
    
    0 讨论(0)
  • 2020-11-22 04:08

    While non of the above solutions was fitting my purpose, this worked for me.

    var pattern = @"^(-?[1-9]+\d*([.]\d+)?)$|^(-?0[.]\d*[1-9]+)$|^0$|^0.0$";
    return Regex.Match(value, pattern, RegexOptions.IgnoreCase).Success;
    

    Example of valid values: "3", "-3", "0", "0.0", "1.0", "0.7", "690.7", "0.0001", "-555", "945465464654"

    Example of not valid values: "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "--1", "-.1", "-0", "00099", "099"

    0 讨论(0)
  • 2020-11-22 04:10

    Regex regex = new Regex ("^[0-9]{1,4}=[0-9]{1,4]$")

    | improve this answer | |
    0 讨论(0)
  • 2020-11-22 04:12

    Here is my working one:

    ^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$
    

    And some tests

    Positive tests:

    string []goodNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};
    

    Negative tests:

    string []badNums={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};
    

    Checked not only for C#, but also with Java, Javascript and PHP

    0 讨论(0)
  • 2020-11-22 04:16

    It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.

    ^\d+$
    
    0 讨论(0)
提交回复
热议问题