“任何正整数,不包括0”的正则表达式是什么

如何改进 ^\d+$以禁用 0

编辑(让它更具体) :

允许的例子:
1
30
111
Examples to disallow:
0
00
-22

是否允许前导零的正数并不重要(例如 022)。

这是用于 JavaJDKRegex 实现的。

189643 次浏览

试试这个:

^[1-9]\d*$

... 和一些填充超过30个字符所以答案限制: ——)。

这是 Demo

找到这个:

^[1-9]|[0-9]{2,}$

有人打它? :)

You might want this (edit: allow number of the form 0123):

^\\+?[1-9]$|^\\+?\d+$

但是,如果是我的话,我会怎么做呢

int x = Integer.parseInt(s)
if (x > 0) {...}

抱歉来晚了,但作业要允许 076,但可能不希望允许 0000000000

在这种情况下,我们需要一个 包含至少一个非零数字的一个或多个数字的字符串

^[0-9]*[1-9][0-9]*$

为了好玩,还有一种替代方法:

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

尽可能多的数字,但至少有一个必须是 [1-9]

你可以尝试一个负面的前瞻性断言:

^(?!0+$)\d+$

^ [1-9] * $是我能想到的最简单的

^\d*[1-9]\d*$

this can include all positive values, even if it is padded by Zero in the front

允许

1

01

10

11等

do not allow

0

00

000等等。

试试这个,这个效果最好,能满足要求。

[1-9][0-9]*

这是样本输出

String 0 matches regex: false
String 1 matches regex: true
String 2 matches regex: true
String 3 matches regex: true
String 4 matches regex: true
String 5 matches regex: true
String 6 matches regex: true
String 7 matches regex: true
String 8 matches regex: true
String 9 matches regex: true
String 10 matches regex: true
String 11 matches regex: true
String 12 matches regex: true
String 13 matches regex: true
String 14 matches regex: true
String 15 matches regex: true
String 16 matches regex: true
String 999 matches regex: true
String 2654 matches regex: true
String 25633 matches regex: true
String 254444 matches regex: true
String 0.1 matches regex: false
String 0.2 matches regex: false
String 0.3 matches regex: false
String -1 matches regex: false
String -2 matches regex: false
String -5 matches regex: false
String -6 matches regex: false
String -6.8 matches regex: false
String -9 matches regex: false
String -54 matches regex: false
String -29 matches regex: false
String 1000 matches regex: true
String 100000 matches regex: true

这应该只允许小数 > 0

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

这个正则表达式匹配0中的任何整数正值:

(?<!-)(?<!\d)[1-9][0-9]*

它适用于两个负向后查,在一个数字前面搜索一个负数,这表明它是一个负数。它也适用于任何大于 -9的负数(例如 -22)。

我的模式是复杂的,但它确切地涵盖了“任何正整数,不包括0”(1-2147483647,不长)。 它是用于十进制数字的,不允许前导零。

^((1?[1-9][0-9]{0,8})|20[0-9]{8}|(21[0-3][0-9]{7})|(214[0-6][0-9]{6})
|(2147[0-3][0-9]{5})|(21474[0-7][0-9]{4})|(214748[0-2][0-9]{3})
|(2147483[0-5][0-9]{2})|(21474836[0-3][0-9])|(214748364[0-7]))$

Any positive integer, excluding 0: ^\+?[1-9]\d*$
任何正整数,包括0: ^(0|\+?[1-9]\d*)$