Python 正则表达式-re

程序开发中,正则表达式有着广泛的应用。
可以使用它基于特定规则来匹配,切分及提取字符串。

对于Python的re模块中常用的方法进行了一些整理。如下。。

    1. 匹配 (match)
import re
reg = r'\d{3}-\d{4}-\d{4}'
re.match(reg, '180-4060-6023')
Output:
匹配成功时:<_sre.SRE_Match object; span=(0, 13), match='180-4060-6023'>
匹配失败时: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'>
    1. 切分 (split)
#使用字符串的split方法,利用空格切分字符串的时候,如包含多个空格时,会分割出空字符串
test='a b   c'
test.split(' ')
Output:
['a', 'b', '', '', 'c']
#如用空格分隔时,如不指定分隔符,可以避免上面的问题
test.split()
Output:
['a', 'b', 'c']
#使用正则的split也可以避免上面的问题
re.split('\s+',test)
Output:
['a', 'b', 'c']
#使用一组特定字符分割
test = '9h 36m 45s'
re.split('[hms]',test)
Output:
 ['9', '36', '45', '']
    1. 分组 (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)
 in ()
----> 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)
 in ()
----> 1 m.groups()
AttributeError: 'NoneType' object has no attribute 'groups'
  • 4 查询(findall)
    findall能够以列表的形式返回字符串中匹配到的子串
import re
word = u'距离报名开始还有5h 13m 58s'
print(re.findall("[0-9]+",word))
Output:
['5', '13', '58']
  • 4 替换(sub)
    sub能将字符串中匹配到的子串替换成指定字符串
import re
word = u'距离报名开始还有5h 13m 58s'
print(re.sub("[^0-9a-z ]+","",word))
Output:
5h 13m 58s
    1. 编译 (compile) 一个正则重复使用时,可考虑使用编译的方法
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')

你可能感兴趣的:(Python 正则表达式-re)