网络编程
位置:首页>> 网络编程>> Python编程>> python中如何使用正则表达式的非贪婪模式示例

python中如何使用正则表达式的非贪婪模式示例

作者:caimouse  发布时间:2022-08-28 08:43:49 

标签:python,正则表达式,非贪婪模式

前言

本文主要给大家介绍了关于python使用正则表达式的非贪婪模式的相关内容,分享出来供大家参考学习,下面话不多说了,来一起详细的介绍吧。

在正则表达式里,什么是正则表达式的贪婪与非贪婪匹配

如:String str="abcaxc";

Patter p="ab*c";

贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。如上面使用模式p匹配字符串str,结果就是匹配到:abcaxc(ab*c)。

非贪婪匹配:就是匹配到结果就好,就少的匹配字符。如上面使用模式p匹配字符串str,结果就是匹配到:abc(ab*c)。

解决这个问题,可以采用: 

正则引擎默认是贪婪的,当出现"*"时,它会尽量去匹配尽可能长的字符串。

 一个用于修正以上问题的可能方案是用"*"的惰性代替贪婪性。你可以在"*"后面紧跟一个问号"?"来达到这一点 
这告诉正则引擎,尽可能少的重复上一个字符。

如下面的例子:


#python 3. 6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
from re_test_patterns import test_patterns

test_patterns(
'abbaabbba',
[('ab*?', 'a followed by zero or more b'),
 ('ab+?', 'a followed by one or more b'),
 ('ab??', 'a followed by zero or one b'),
 ('ab{3}?', 'a followed by three b'),
 ('ab{2,3}?', 'a followed by two to three b')],
)

输出结果如下:


'ab*?' (a followed by zero or more b)

'abbaabbba'
'a'
...'a'
....'a'
........'a'

'ab+?' (a followed by one or more b)

'abbaabbba'
'ab'
....'ab'

'ab??' (a followed by zero or one b)

'abbaabbba'
'a'
...'a'
....'a'
........'a'

'ab{3}?' (a followed by three b)

'abbaabbba'
....'abbb'

'ab{2,3}?' (a followed by two to three b)

'abbaabbba'
'abb'
....'abb'

来源:http://blog.csdn.net/caimouse/article/details/78170717

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com