zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

Python正则表达式 实现 字符串 定义 文本 匹配 最短
2023-09-14 08:59:26 时间

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

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

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个被引号包围的字符串

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

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