Python(八)正则表达式

1.正则表达式
python中用match()函数判断是否匹配

>>> import re
>>> re.match(r'^\d{3}\-\d{3,8}$','010-12345')
<re.Match object; span=(0, 9), match='010-12345'>
>>> re.match(r'^\d{3}\-\d{3,8}$','010 12345')
>>> 

若匹配返回match,否则返回None
2.分组
正则表达式提供分组功能,这是一个强大的功能

>>> m=re.match(r'^(\d{3})-(\d{3,8})$','010-12345')
	       
>>> m
	       
<re.Match object; span=(0, 9), match='010-12345'>
>>> m.group(0)
	       
'010-12345'
>>> m.group(0)
	       
'010-12345'
>>> m.group(1)
	       
'010'
>>> m.group(2)
	       
'12345'

3.贪婪匹配
正则表达式默认贪婪匹配,如下

>>> re.match(r'^(\d+)(0*)$','102300').groups()
	       
('102300', '')

此时想匹配出后面的0,需要用非贪婪匹配,在后面加?

>>> re.match(r'^(\d+?)(0*)$','102300').groups()
	       
('1023', '00')

猜你喜欢

转载自blog.csdn.net/qq_37282683/article/details/88545004
今日推荐