JS - Regex for number without leading zero, or just zero

后端 未结 1 637
青春惊慌失措
青春惊慌失措 2021-01-27 03:36

I am trying to write a regular expression for currency (no commas or $ signs or periods; just integers), but I am hitting a wall.

I need a the number (as a string) to m

相关标签:
1条回答
  • 2021-01-27 04:01

    Use the following regex:

    /^(?:[1-9][0-9]*|0)$/
    

    Details

    • ^ - start of string
    • (?: - start of an alternation group:
      • [1-9][0-9]* - a digit from 1 to 9 and then any 0+ digits
      • | - or
      • 0 - a 0
    • ) - end of the group
    • $ - end of the string.

    See the regex demo.

    JS demo:

    var regex = /^(?:[1-9][0-9]*|0)$/;
    var testCases = ['0', '12345', '0123', '456'];
    for (var i in testCases) {
      var result = regex.test(testCases[i]); 
      console.log(testCases[i] + ': ' + result);      
    }

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