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

IT小君   2021-09-30T05:48:03

怎样才能^\d+$改进禁止0

编辑(使其更具体):

允许示例:
1
30
111
禁止示例:
0
00
-22

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

这是用于 Java JDK Regex 实现的。

评论(13)
IT小君

尝试这个:

^[1-9]\d*$

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

这是演示

2021-09-30T05:48:04   回复
IT小君

抱歉来晚了,但 OP 想要允许076但可能不想允许0000000000

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

^[0-9]*[1-9][0-9]*$
2021-09-30T05:48:04   回复
IT小君

您可以尝试否定前瞻断言:

^(?!0+$)\d+$
2021-09-30T05:48:04   回复
IT小君

试试这个,这个最能满足要求。

[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
2021-09-30T05:48:04   回复
IT小君

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

这可以包括所有正值,即使它在前面被零填充

允许

1

01

10

11 等

不允许

0

00

000 等

2021-09-30T05:48:05   回复
IT小君

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

2021-09-30T05:48:05   回复
IT小君

得到了这个:

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

有人打过吗?:)

2021-09-30T05:48:05   回复
IT小君

只是为了好玩,另一种使用前瞻的替代方法:

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

数字任意多,但至少有一个必须是[1-9].

2021-09-30T05:48:05   回复
IT小君

你可能想要这个(编辑:允许表格编号0123):

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

然而,如果是我,我会这样做

int x = Integer.parseInt(s)
if (x > 0) {...}
2021-09-30T05:48:06   回复
IT小君

此 RegEx 匹配任何 0 中的正整数:

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

它与两个负向后视器一起使用,它们在数字之前搜索一个减号,这表明它是一个负数。它也适用于任何大于 -9 的负数(例如 -22)。

2021-09-30T05:48:06   回复
IT小君

我的模式很复杂,但它完全涵盖了“任何正整数,不包括 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]))$
2021-09-30T05:48:06   回复
IT小君

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

2021-09-30T05:48:06   回复
IT小君

这应该只允许小数 > 0

^([0-9]\.\d+)|([1-9]\d*\.?\d*)$
2021-09-30T05:48:07   回复