我试图匹配三个y
并在两侧都带有数字的模式:
1yyy5
在上面的示例中,此方法有效:
\d{1}y{3}\d{1}
现在,如果我在y
之一之间添加了一个附加字符,它将失败:
1yyay5
我如何使用{}
(或其他方式?)来匹配单个数字之间的出现,即使它们不是连续的呢?只要两个数字之间恰好存在三个y
所需结果:
1yyy5 //should match because three y between 2 numbers
1yyaaay5 // should match because there are three y between two numbers
3..!y3777 // would fail, only one y
..@#9naymnymmmyptjr8 // pass, there are exactly 3 y between 9 and 8
1yyyy2 /fail, 1 to many y. must be exactly 3
答案 0 :(得分:2)
这是工作:
\d(?:[^y\d]*y){3}[^y\d]*\d
说明:
\d # a digit.
(?: # start non capture group.
[^y\d]* # 0 or more non y or digit.
y # 1 y.
){3} # end group, must appear 3 times.
[^y\d]* # 0 or more non y or digit.
\d # a digit.