Python 匹配贪婪短语搜索。

标签 python regex

我有正则表达式匹配要求。我想匹配一个完整的短语而不是单个子标记。这是一个例子

In [21]: re.findall(r"""don't|agree|don't agree""", "I don't agree to this", re.IGNORECASE)
Out[21]: ["don't", 'agree']

我希望它匹配“不同意”,而不是分别匹配不同意和同意

任何帮助。

最佳答案

将最长的字符串放在前面:

re.findall(r"don't agree|don't|agree", "I don't agree to this", re.IGNORECASE)

或使用可选组:

re.findall(r"don't(?: agree)?|agree", "I don't agree to this", re.IGNORECASE)

关于Python 匹配贪婪短语搜索。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22559890/

相关文章:

python - 避免执行模拟类的 __init__

mysql - 仅获取包含少于 4 位数字的行

Python更新两个具有相同列和一些不同行的数据框

python - 有没有办法反转 TensorFlow 中的图?

regex - 如何在 .htaccess 的文件 block 中使用多个路径?

php - 强密码验证 laravel

regex - 电子邮件正则表达式验证器不允许返回

arrays - 从数组中删除空白正则表达式命中

python - 理解Python的导入__main__

python - 我什么时候应该使用 *args?