python - 正则表达式如何{m,n}?在 Python 中工作?

标签 python regex

来自 re 模块的 Python 文档:

{m,n}?

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.

我对它的工作原理感到困惑。这与 {m} 有何不同?我看不出模式匹配超过 m 次的情况。如果连续 m+1 次重复,则也有 m 次。我错过了什么?

最佳答案

鉴于,仅包含 a{3,5}? 的正则表达式和具有模式:a{3} 的正则表达式确实会匹配相同的内容(即 re.match(r'a{3,5}?', 'aaaaa').group(0)re.match(r'a{3}', 'aaaaa ').组(0) 都将返回 'aaa'),当您查看包含这两个元素的模式时,模式之间的区别就会变得很清楚。假设您的模式是 a{3,5}?b,那么 aaabaaaabaaaaab 将是匹配。如果您只使用 a{3}b,那么只有 aaab 会匹配。 aaaabaaaaab 不会。

请查看 Shashank 的回答以获取可以进一步消除这种差异的示例,或者测试您自己的示例。我发现这个 site是用于测试 python 正则表达式的好资源。

关于python - 正则表达式如何{m,n}?在 Python 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29852042/

相关文章:

java - 常规Exp : Matcher: how to get last occurence in the group

python - 如何使用 OpenCV 将给定坐标转换为 Python 中的 KAZE 关键点

regex - 在 scala 中获取重复的正则表达式组

python - 如何通过 requests-oauthlib token 获取避免 InValidClientError?

python - cli 中的 argparse Python 模块

java - 无法使用正则表达式检索行中的最后一个单词

c# - 如何使用正则表达式进行不区分大小写的字符串替换?

javascript - 我有输入文本框,应采用 $ 和 £ 货币符号,并在用户键入任何其他特殊字符时发出警告

python - 使用诱变剂修复 ID3 标签的编码

Python添加到MySQL数据库