2

我是正则表达式的新手,对于我正在处理的项目,我需要验证一个字段以查看输入的 10 位数字是否包含所有相同的数字。

我找到了以下解决方案:

([1-9])\\1{9}

来源: http: //www.coderanch.com/t/461871/java/java/Check-if-number-contains-all

我试图用谷歌搜索它,但没有任何东西可以解释这个表达式在做什么。我想知道是否有人可以解释这个表达式是如何工作的。

4

2 回答 2

3

它是这样工作的:

([1-9])   // Capture any number 1-9 and store it as the first "capture"
\1        // Substitute the first "capture" as raw text into the regex
{9}       // Match that raw text another 9 times (i.e. 10 in total)

确保它0000000000不应该匹配你的表达,因为这不匹配[1-9]

于 2012-10-02T13:48:29.997 回答
1

这全都是关于captured groups

([1-9])是一个capture group捕获 1-9 之间的单个数字

\1{9}first capture group重复 9 次的 ie ([1-9])..

例子

您可以拥有一个匹配内容的正则表达式,该内容始终位于匹配的标签名称之间。

所以,使用这个正则表达式

<(.*?)>(.*?)<\1>

对于以下每个输入

<party>At Garden<party>
<dance>With GirlFriend<dance>
<drink>risky<drive>

您将在第 2 组捕获

At Garden
With GirlFriend
//risky would not match
于 2012-10-02T13:50:38.883 回答