python - 匹配所有 [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']。
提前致谢!
解决方案
您可以使用带有反向引用的负前瞻来避免匹配重复项:
re.findall(r'([A-Z])(?!.*\1.*$)', '(B or P) and (P or not Q)')
这将返回:
['B', 'P', 'Q']
推荐阅读
- ruby-on-rails - 如果表列在更新时发生更改,Assign_attributes 仅分配子 attr_accessor 值
- java - PowerShell 脚本不返回
- c++ - 如何在 C++ 中为用户定义的结构初始化最小值?
- python - 在 jupyter notebook 中,我使用 pandas 打开了一个 csv 文件,其中包含与游戏相关的数据,包括上次更新日期
- r - 我找不到注释 gpl20995 和 6244 的软件包
- python - TypeError:'str'对象在尝试通过变量运行以写入它们时不支持项目分配
- python - Armstrong 数字的 Python 程序未正确输出
- json - 是否可以将值设置为低于零和最大值,JsonSchema?
- vue.js - 将 Vue 组件转换为 Vuetify 组件
- java - 启动新 Intent 时 Android 应用程序崩溃