使用正则表达式确保字符串的唯一字符数大于特定数字

问题描述

我正在寻找是否有可能使用正则表达式来验证字符串的唯一字符数是否大于特定数字。例如:AAABBB将失败,要求唯一计数大于2,但AABBCC将通过。

有人请指教吗?

解决方法

捕获第一个字符。然后,通过使用向后引用,重复该字符尽可能多的次数,并捕获其后的下一个字符,以确保它与第一个字符通过负向前瞻不同。再次将这两个字符重复多次,然后使用相同的否定超前技巧来匹配第三个字符。

^          # Beginning of string
(.)        # Capture first character
\1*        # Repeat first character
(?!\1)(.)  # Capture second character,which is not first character
(?:\1|\2)* # Repeat first or second character
(?!\1|\2)  # Ensure next character is not first or second; you now have 3 distinct
.+         # Match anything up to
$          # end of the string

https://regex101.com/r/TxT7r7/1

(可以用^(.).*(?!\1)(.).*(?!\1|\2).+$使样式更漂亮,但精度不高)