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

Zee*_*mee 81 java regex

怎么可以^\d+$改善不允许0

编辑(使其更具体):

允许的示例:
1
30
111
不允许的示例:
0
00
-22

如果允许或不允许具有前导零的正数(例如022),则无关紧要.

这适用于Java JDK Regex实现.

Tom*_*icz 162

试试这个:

^[1-9]\d*$
Run Code Online (Sandbox Code Playgroud)

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

  • @mtahmed:`^ [1-9] + $`不允许10 (17认同)
  • 但是“01”呢? (3认同)

Ray*_*oal 66

很抱歉迟到但OP希望允许,076但可能不想允许0000000000.

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

^[0-9]*[1-9][0-9]*$
Run Code Online (Sandbox Code Playgroud)

  • 显然比接受的答案更好,因为它允许'076` (3认同)
  • +1 考虑角落案例!顺便说一句,此模式将完全相同: **`^0*[1-9]\d*$`** 因为第一个 `[0-9]*` 仅在找到 `[1-9]` 之前处于活动状态第一个非零,即它只在有初始零 (`0*` ) 之前处于活动状态。 (2认同)

Kar*_*ome 15

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

^(?!0+$)\d+$
Run Code Online (Sandbox Code Playgroud)

  • 天啊,我很害怕. (25认同)

小智 8

试试这个,这个最适合要求.

[1-9][0-9]*
Run Code Online (Sandbox Code Playgroud)

这是示例输出

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
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但与接受的答案`[1-9]\d*`相比,它没有增加任何价值或优雅. (2认同)

man*_*noj 7

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

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

允许

1

01

10

11等

不允许

0

00

000等..