最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to match integer without leading zero (s) - Stack Overflow

programmeradmin3浏览0评论

I have this regex to match integers

var reg = /^\d+$/;

I also want it ensure that 1 or more zeros are not placed at the front

var reg = ^[0\d]\d+$

This is what I have so far but doesnt work.

How can this be done?

Passing tests

1
12
1232164

Failing tests

0
01
00004241
fbhf
""
a123

I have this regex to match integers

var reg = /^\d+$/;

I also want it ensure that 1 or more zeros are not placed at the front

var reg = ^[0\d]\d+$

This is what I have so far but doesnt work.

How can this be done?

Passing tests

1
12
1232164

Failing tests

0
01
00004241
fbhf
""
a123
Share Improve this question edited Oct 30, 2013 at 0:36 ojhawkins asked Oct 30, 2013 at 0:31 ojhawkinsojhawkins 3,27816 gold badges53 silver badges69 bronze badges 7
  • 01 should pass? can't understand what you need to match – X-Pippes Commented Oct 30, 2013 at 0:33
  • I want to match a integer that doesnt start with 1 or more zeros @X-Pippes – ojhawkins Commented Oct 30, 2013 at 0:34
  • 3 I think you want: var reg = ^[1-9]\d+$ – Jeanne Boyarsky Commented Oct 30, 2013 at 0:34
  • Thanks Jeanne, please add a answer :) – ojhawkins Commented Oct 30, 2013 at 0:36
  • @Jeanne put \d* instead of \d+, otherwise your regex don't accept only one digit. – X-Pippes Commented Oct 30, 2013 at 0:39
 |  Show 2 more comments

3 Answers 3

Reset to default 12

I think you want:

var reg = "^[1-9]\d*$";

If you have to match an empty string, you are best off checking for empty string before running the reg exp. Otherwise, you could do it in this harder to read regex:

var reg = "^(|[1-9]\d*)$";

It checks for an empty string or one or more digits beginning with zero.

try this regex

[1-9]+[0-9]*

this will make you have a number that not start with zero

Try this solution:

0*([1-9][0-9]*|0)

发布评论

评论列表(0)

  1. 暂无评论