python - 使用 re.match 查找重复字符

标签 python regex python-2.7

我想弄清楚为什么下面的代码打印“2”而不是“1”

import re

line = "9111222"
m = re.match( r'.*(\w)\1+', line)
print m.group(1)

我知道 re.match 尝试匹配字符串的开头,但我假设它会看到“111”并打印“1”

最佳答案

正则表达式中的* 量词是贪婪,这意味着它将尝试匹配尽可能多的匹配项。在您的字符串中,91112(2)2 将允许 .* 匹配最多的字符,因此这是引擎选择的匹配项,倒数第二个 2 被捕获。

参见 https://regex101.com/r/IkM5gX/2

关于python - 使用 re.match 查找重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40814434/

相关文章:

python - “heroku run python manage.py migrate”失败并出现错误 'Error R13 (Attach error) -> Failed to attach to process'

python - Tensorflow - 不兼容的形状

python - 谷歌分析 API 问题

python - 在 python 中从 excelsheet 中读取特定的单元格值

python - 迭代月份列表时插入 None

python - 值错误 : Random forest classification by scikit learn

regex - vim 模式匹配两个标记,中间没有另一个给定的标记

python - 连接多个正则表达式的输出

c# - 匹配 href 的正则表达式,但没有媒体文件

python - 为每个唯一的 id 收集 python 中 csv 的所有值