python-正则表达式1消-?号除贪婪模式

import re
# 判断是否包含b
# line = "booooooobby123"
# regex_str = "^b.*"
# if re.match(regex_str, line) :
#     print('yes')

# 结果是bb 原因:正则表达式是一种贪婪的模式 一直会匹配到最后一种返回
line = 'booooooooobby123'
regex_str = ".*(b.*b).*"
match_obj = re.match(regex_str, line)
if match_obj:
    print(match_obj.group(1))

# 结果是booooooooobb ?表示 匹配前面的子表达式零次或一次 在这里可以理解成解除贪婪的模式
line = 'booooooooobby123'
regex_str = ".*?(b.*b).*"
match_obj = re.match(regex_str, line)
if match_obj:
    print(match_obj.group(1))


# 结果返回booooooooob 这个是正确的写法 加了两个?解除贪婪的模式
line = 'booooooooobby123'
regex_str = ".*?(b.*?b).*"
match_obj = re.match(regex_str, line)
if match_obj:
    print(match_obj.group(1))

  

原文地址:https://www.cnblogs.com/shaoshao/p/10957941.html