re正则表达式7_{}

curly brackets {}

instead of one number, you can specify a range by writing a minimum,a comma,and a maximum in between the curly brackets.

for example, the regex (ha) {3,5} will match 'hahaha' ,'hahahaha',and 'hahahahaha'

{3,5}是索引范围,3表示最小值,5表示最大值。

(ha){3}  =(ha)(ha)(ha)

(ha){3,5}=

((ha)(ha)(ha)|(ha)(ha)(ha)(ha)|(ha)(ha)(ha)(ha)(ha))

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import re
#{3}表示倍数
re1=re.compile(r'(ha){3}')
mo1=re1.search('hahaha')
print("mo1.group():",mo1.group())

#此处找不到匹配的一个ha
mo2=re1.search('ha')
mo2==None

greedy_re=re.compile(r'(ha){3,5}')
greedy_mo=greedy_re.search('hahahahaha') #五个ha可以匹配3个,4个或5个,贪婪搜索抓取最长的字符串
print("greedy_mo.group():",greedy_mo.group())

nonegreedy_re=re.compile(r'(ha){3,5}?')
nonegreedy_mo=nonegreedy_re.search('hahahahaha')
print("nonegreedy_mo.group():",nonegreedy_mo.group())

贪婪与非贪婪搜索

Python默认使用贪婪搜索,贪婪搜索意味着匹配最长的字符串。

非贪婪式搜索意味着匹配最短字符串。{}?表示非贪婪搜索

?在re正则表达式中有两个意思:

(1)非贪婪搜索

(2)flagging an optional group

原文地址:https://www.cnblogs.com/webRobot/p/5207614.html