首页 > 解决方案 > 匹配所有 [AZ] 但不匹配

问题描述

我需要匹配字符串中的所有大写字母,但不是我一直在使用的 python 中相同字母的重复

from re import compile

regex = compile('[A-Z]')
variables = regex.findall('(B or P) and (P or not Q)')

但这将匹配 ['B', 'P', 'P', 'Q'] 但我需要 ['B', 'P', 'Q']。

提前致谢!

标签: pythonregex

解决方案


您可以使用带有反向引用的负前瞻来避免匹配重复项:

re.findall(r'([A-Z])(?!.*\1.*$)', '(B or P) and (P or not Q)')

这将返回:

['B', 'P', 'Q']

推荐阅读