Regex that matches integers only

前端 未结 10 535
执笔经年
执笔经年 2020-11-30 09:56

I\'m currently using the pattern: \\b\\d+\\b, testing it with these entries:

numb3r 
2
3454 
3.214
test

I only want it to catc

相关标签:
10条回答
  • 2020-11-30 10:00

    ^(-+)?[1-9][0-9]*$ starts with a - or + for 0 or 1 times, then you want a non zero number (because there is not such a thing -0 or +0) and then it continues with any number from 0 to 9

    0 讨论(0)
  • 2020-11-30 10:03

    All you want is the below regex:

    ^\d+$
    
    0 讨论(0)
  • 2020-11-30 10:03
    ^([+-]?[0-9]\d*|0)$
    

    will accept numbers with leading "+", leading "-" and leadings "0"

    0 讨论(0)
  • 2020-11-30 10:06

    This solution matches integers:

    • Negative integers are matched (-1,-2,etc)
    • Single zeroes are matched (0)
    • Negative zeroes are not (-0, -01, -02)
    • Empty spaces are not matched ('')
    /^(0|-*[1-9]+[0-9]*)$/
    
    0 讨论(0)
  • 2020-11-30 10:08

    This worked in my case where I needed positive and negative integers that should NOT include zero-starting numbers like 01258 but should of course include 0

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

    Example of valid values: "3", "-3", "0", "-555", "945465464654"

    Example of not valid values: "0.0", "1.0", "0.7", "690.7", "0.0001", "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "+100", "--1", "-.1", "-0", "00099", "099"

    0 讨论(0)
  • 2020-11-30 10:15

    I would add this as a comment to the other good answers, but I need more reputation to do so. Be sure to allow for scientific notation if necessary, i.e. 3e4 = 30000. This is default behavior in many languages. I found the following regex to work:

    /^[-+]?\d+([Ee][+-]?\d+)?$/;
    //          ^^              If 'e' is present to denote exp notation, get it
    //             ^^^^^          along with optional sign of exponent
    //                  ^^^       and the exponent itself
    //        ^            ^^     The entire exponent expression is optional
    
    0 讨论(0)
提交回复
热议问题