这可以在一个正则表达式中完成吗?

use*_*287 6 ruby regex

我需要一个正则表达式匹配一个字符串:

  • 只有数字0-9和空格
  • 所有数字必须相同
  • 应该至少有2位数
  • 应该以数字开头和结尾

火柴:

11
11111
1  1 1 1 1
1  1
11 1 1 1 1 1
1           1
1    1      1

无匹配:

1             has only one digit
11111         has space at the end
 11111        has space at beginning
12            digits are different
11:           has other character

我知道每个要求的正则表达式.这样我就会使用4个正则表达式测试.我们可以在一个正则表达式中完成吗?

cod*_*ict 14

是的,它可以在一个正则表达式中完成:

^(\d)(?:\1| )*\1$
Run Code Online (Sandbox Code Playgroud)

Rubular链接

说明:

^      - Start anchor
(      - Start parenthesis for capturing
 \d    - A digit
)      - End parenthesis for capturing
(?:    - Start parenthesis for grouping only
\1     - Back reference referring to the digit capture before
|      - Or
       - A literal space
)      - End grouping parenthesis
*      - zero or more of previous match
\1     - The digit captured before
$      - End anchor
Run Code Online (Sandbox Code Playgroud)

  • @Gareth:不是他们没有的角色课! (2认同)