1

我使用以下正则表达式匹配长度为 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 个数字呢?

示例:http ://regexr.com?32u40

4

1 回答 1

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.
于 2012-11-25T20:09:23.063 回答