匹配跳过字符的出现次数
Matching number of occurrences skipping chars
我试图匹配一个模式,它是三个 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
这个可以胜任:
\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.
我试图匹配一个模式,它是三个 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
这个可以胜任:
\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.