Regex for numbers only

后端 未结 18 2260
野性不改
野性不改 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:20

    Sorry for ugly formatting. For any number of digits:

    [0-9]*
    

    For one or more digit:

    [0-9]+
    
    0 讨论(0)
  • 2020-11-22 04:22

    Another way: If you like to match international numbers such as Persian or Arabic, so you can use following expression:

    Regex = new Regex(@"^[\p{N}]+$");
    

    To match literal period character use:

    Regex = new Regex(@"^[\p{N}\.]+$");
    
    0 讨论(0)
  • 2020-11-22 04:23

    Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:

    regex = new Regex("^[0-9]+$");
    

    The ^ will anchor the beginning of the string, the $ will anchor the end of the string, and the + will match one or more of what precedes it (a number in this case).

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

    Regex for integer and floating point numbers:

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

    A number can start with a period (without leading digits(s)), and a number can end with a period (without trailing digits(s)). Above regex will recognize both as correct numbers.

    A . (period) itself without any digits is not a correct number. That's why we need two regex parts there (separated with a "|").

    Hope this helps.

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

    If you need to check if all the digits are number (0-9) or not,

    ^[0-9]+$
    

    1425 TRUE

    0142 TRUE

    0 TRUE

    1 TRUE

    154a25 FALSE

    1234=3254 FALSE

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

    Use beginning and end anchors.

     Regex regex = new Regex(@"^\d$");
    

    Use "^\d+$" if you need to match more than one digit.

    0 讨论(0)
提交回复
热议问题