正则表达式匹配精确的字符数?

我需要一个 正则表达式,将匹配任何三个大写字母,所以 AAA 或 ABC 或 DKE。但它不能匹配四个或更多,像 AAAA 或 ABCDEF 或 abbB。

我的解决方案: ^([A-Z][A-Z][A-Z])$

问题 :

  1. 是这样吗?
  2. 有没有其他的方法,只是为了学习?
162279 次浏览

What you have is correct, but this is more consice:

^[A-Z]{3}$

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.