【python cookbook】【字符串与文本】7.定义实现最短匹配的正则表达式

问题:使用正则表达式对文本模式匹配,将识别出来的最长的可能匹配修改为找出最短的可能匹配

解决方法:在匹配模式中的*操作符后加上?修饰符

import re

# Sample text
text = 'Computer says "no." Phone says "yes."'

# (a) Regex that finds quoted strings - longest match
str_pat = re.compile(r'"(.*)"')
print(str_pat.findall(text))

# (b) Regex that finds quoted strings - shortest match
str_pat = re.compile(r'"(.*?)"')
print(str_pat.findall(text))
>>> ================================ RESTART ================================
>>> 
['no." Phone says "yes.']
['no.', 'yes.']
>>> 

(a)例子中被错误的匹配成2个被引号包围的字符串

补充:本节提到了一个当编写含有句点(.)字符的正则表达式时会遇到的问题。

在模式匹配中,句点除了换行符之外可匹配任意字符。

原文地址:https://www.cnblogs.com/apple2016/p/5790837.html