import re
content = 'hello 1234567 World_This is a Regex Demo'
# 贪婪匹配
result1 = re.match('^he.*(\d+).*Demo$', content)
# 非贪婪匹配
result2 = re.match('^he.*?(\d+).*Demo$', content)
print(result1) # <_sre.SRE_Match object; span=(0, 40), match='hello 1234567 World_This is a Regex Demo'>
print(result1.group(1)) # 7
print(result2) # <_sre.SRE_Match object; span=(0, 40), match='hello 1234567 World_This is a Regex Demo'>
print(result2.group(1)) # 1234567
# 非贪婪匹配放在末尾,可能匹配不到任何内容
content = 'http://baidu.com/zhangsan'
result3 = re.match('http.*?com/(.*?)', content)
result4 = re.match('http.*?com/(.*)', content)
print(result3.group(1)) #
print(result4.group(1)) # zhangsan
Python 正则表达式-贪婪与非贪婪匹配
最新推荐文章于 2023-08-19 21:34:03 发布