最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

regex - JavaScript match numbers that are not zero or start with zero - Stack Overflow

matteradmin2PV0评论

I have the following regex that I'm trying to ONLY allow numbers like:

1, 2, 3, 10, 11, 24 etc

and NOT 0, 01, etc

if (!$(this).text().match(/^[1-9][0-9]/g)) {


}

Is this correct? As it doesn't allow numbers like 1, 2, 3 but is 11, 12 etc

I have the following regex that I'm trying to ONLY allow numbers like:

1, 2, 3, 10, 11, 24 etc

and NOT 0, 01, etc

if (!$(this).text().match(/^[1-9][0-9]/g)) {


}

Is this correct? As it doesn't allow numbers like 1, 2, 3 but is 11, 12 etc

Share Improve this question asked Jun 25, 2013 at 9:15 CameronCameron 28.9k102 gold badges289 silver badges490 bronze badges 4
  • 1 Can you not just check whether the first character is 0? Or do you need to allow 0.5, etc? – Andrzej Doyle Commented Jun 25, 2013 at 9:17
  • would running parseInt( $(this).text(), 10 ) solve your problem? – Andy Ray Commented Jun 25, 2013 at 9:18
  • @AndrzejDoyle No only whole numbers, so checking for leading zero would work – Cameron Commented Jun 25, 2013 at 9:19
  • Should 230345734872590343598340952342342483485 match? – georg Commented Jun 25, 2013 at 9:31
Add a ment  | 

2 Answers 2

Reset to default 10

You need to specify a * after second [0-9] to match zero or more digits. In addition to one digit numbers, this will also fail to match more than two digit numbers. Correct regular expression is ^[1-9][0-9]*.

Try using Replace ()

if (!$(this).text().replace(/^(-?)0+/,'').match(/[1-9]?[0-9]*/))
Post a comment

comment list (0)

  1. No comments so far