我使用以下正则表达式来匹配长度为4且具有1个数字和3个大写字母的单词:
\b(?=[A-Z]*\d[A-Z]*\b)[A-Z\d]{4}\b
我想知道的是我需要修改表达式来过滤掉长度为10的单词,其中包含0-2个数字。
\b(?=[A-Z]*\d[A-Z]*\b)[A-Z\d]{10}\b
这适用于1个数字出现,但我如何将其扩展为过滤0和2数字呢?
答案 0 :(得分:4)
将长度检查放入前瞻:
\b(?=[A-Z\d]{10}\b)(?:[A-Z]*\d){0,2}[A-Z]*\b
<强>解释强>
\b # Start at a word boundary
(?= # Assert that...
[A-Z\d]{10} # 10 A-Z/digits follow
\b # until the next word boundary.
) # (End of lookahead)
(?: # Match...
[A-Z]* # Any number of ASCII uppercase letters
\d # and exactly one digit
){0,2} # repeat 0, 1 or 2 times.
[A-Z]* # Match any number of letters
\b # until the next word boundary.