程序開發(fā)中,正則表達(dá)式有著廣泛的應(yīng)用睦裳。
可以使用它基于特定規(guī)則來(lái)匹配造锅,切分及提取字符串。
對(duì)于Python的re模塊中常用的方法進(jìn)行了一些整理廉邑。如下哥蔚。。
- 匹配 (match)
import re
reg = r'\d{3}-\d{4}-\d{4}'
re.match(reg, '180-4060-6023')
Output:
匹配成功時(shí):<_sre.SRE_Match object; span=(0, 13), match='180-4060-6023'>
匹配失敗時(shí):None
### (1)匹配不包含某特定字符串的例子
import re
test_str_1 = 'i am a student! my name is jay'
test_str_2 = 'i am a teacher! my name is lily'
reg = '^(?!.*?student).*$'
print (re.match(reg, test_str_1))
print (re.match(reg, test_str_2))
Output:
None
<_sre.SRE_Match object; span=(0, 31), match='i am a teacher! my name is lily'>
- 切分 (split)
#使用字符串的split方法蛛蒙,利用空格切分字符串的時(shí)候糙箍,如包含多個(gè)空格時(shí),會(huì)分割出空字符串
test='a b c'
test.split(' ')
Output:
['a', 'b', '', '', 'c']
#如用空格分隔時(shí)牵祟,如不指定分隔符深夯,可以避免上面的問(wèn)題
test.split()
Output:
['a', 'b', 'c']
#使用正則的split也可以避免上面的問(wèn)題
re.split('\s+',test)
Output:
['a', 'b', 'c']
#使用一組特定字符分割
test = '9h 36m 45s'
re.split('[hms]',test)
Output:
['9', '36', '45', '']
- 分組 (group)
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
m.group(0)
Output:
'010-12345'
m.group(1)
Output:
'010'
m.group(2)
Output:
'12345'
m.groups()
Output:
('010', '12345')
m.group(3)
Output:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-13-71a2c7935517> in <module>()
----> 1 m.group(3)
IndexError: no such group
m = re.match(r'^(\d{3})-(\d{8})$', '010-12345')
m.groups()
Output:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-84a8d9c174e2> in <module>()
----> 1 m.groups()
AttributeError: 'NoneType' object has no attribute 'groups'
- 4 查詢(findall)
findall能夠以列表的形式返回字符串中匹配到的子串
import re
word = u'距離報(bào)名開始還有5h 13m 58s'
print(re.findall("[0-9]+",word))
Output:
['5', '13', '58']
- 4 替換(sub)
sub能將字符串中匹配到的子串替換成指定字符串
import re
word = u'距離報(bào)名開始還有5h 13m 58s'
print(re.sub("[^0-9a-z ]+","",word))
Output:
5h 13m 58s
- 編譯 (compile) 一個(gè)正則重復(fù)使用時(shí),可考慮使用編譯的方法
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
re_telephone.match('010-12345').groups()
Output:
('010', '12345')
re_telephone.match('010-8086').groups()
Output:
('010', '8086')