0

我正在尝试在 Java 中创建一个正则表达式来验证具有以下约束的数字:

  1. 数字可以是任意长度,但只能包含数字
  2. 第一个数字可以是 0 - 9
  3. 后续数字可以是 0 - 9,但其中一位数字必须为非零。

例如:042004359有效,但0000000000无效。

4

4 回答 4

3

\\d+[1-9]\\d*应该工作,我想。

于 2012-08-13T21:46:43.857 回答
1

This should do what you need:

/^(?=.*[1-9])([0-9]+)$/

Whilst it matches all of digits [0-9] it contains a lookahead that makes sure there is at least one of [1-9].

I am fairly certain that Java allows can use lookaheads.

EDIT: This regular expression test page seems to imply that it can.

EDIT: If 0 is valid, then you can use this:

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

This will make an exception for 0 on its own (notice the OR operator).

于 2012-08-13T22:22:28.653 回答
0
^(\d{1})(\d*?[1-9]{1}\d*)*$

^(\d{1}) - 行必须以 1 位数字开头
(\d*?[1-9]{1}\d*)*$ - 行必须以零个或多个 0-9 位数字结尾(? 保守),然后是 1 个 1-9 位,然后是零个或多个数字。这种模式可以重复零次或多次。

适用于:

100000
100100
1010200
1
2

也许这太复杂了,大声笑。

于 2012-08-13T22:17:55.550 回答
0

这是使用环视的一种解决方案:(?<=\D|^)\d+(?=[1-9])\d*

(?<=\D|^)   # lookbehind for non-digit or beginning of line
\d+         # match any number of digits 0-9
(?=[1-9])   # but lookahead to make sure there is 1-9
\d*         # then match all subsequent digits, once the lookahead is satisfied
于 2012-08-13T22:33:52.480 回答