Regex that matches integers only

前端 未结 10 536
执笔经年
执笔经年 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:20

    Similar to manojlds but includes the optional negative/positive numbers:

    var regex = /^[-+]?\d+$/;
    

    EDIT

    If you don't want to allow zeros in the front (023 becomes invalid), you could write it this way:

    var regex = /^[-+]?[1-9]\d*$/;
    

    EDIT 2

    As @DmitriyLezhnev pointed out, if you want to allow the number 0 to be valid by itself but still invalid when in front of other numbers (example: 0 is valid, but 023 is invalid). Then you could use

    var regex = /^([+-]?[1-9]\d*|0)$/
    
    0 讨论(0)
  • 2020-11-30 10:21

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

    It matches positive, negative numbers as well as zeros.

    It doesn't match input like 00, -0, +0, -00, +00, 01.

    Online testing available at http://rubular.com/r/FlnXVL6SOq

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

    You could use lookaround instead if all you want to match is whitespace:

    (?<=\s|^)\d+(?=\s|$)
    
    0 讨论(0)
  • 2020-11-30 10:23

    This just allow positive integers.

    ^[0-9]*[1-9][0-9]*$
    
    0 讨论(0)
提交回复
热议问题