目录
1 用处
字符串
字符串的一系列操作并不能满足完整的特殊需求
2 格式
import re
re.findall(‘规则’, '字符串’)
3 元字符 . 通配符(可代表\n外所有)
例如 re.findall(‘w…l’, ‘hello world’)
返回worl,中间两个点代表两个任意字符
4 元字符 ^ 尖角符(从开头匹配,取反)
'''从开头匹配'''
s = re.findall('^w..l', 'hello world') #[]
s = re.findall('^h..l', 'hello world') #['hell']
'''在中括号内表示中括号内取反'''
s = re.findall('[^l]o', 'hello world') #['wo']
5 元字符 $ (从结尾匹配)
s = re.findall('lo', 'hello worlo') #['lo', 'lo']
s = re.findall('lo$', 'hello worlo') #['lo']
6 元字符 * 重复匹配符[0, +∞)都可 只重复其前面的
s = re.findall('l*o', 'hello worlo') #['llo', 'o', 'lo']
7 元字符 + 重复匹配符[1, +∞)都可 只重复其前面的
s = re.findall('l+o', 'hello worlo') #['llo', 'lo']
8 元字符 ? 重复匹配符[0,1] 都可 只重复其前面的(其他重复匹配符后面加?实现惰性匹配)
s = re.findall('l?o', 'hello worlo') #['lo', 'o', 'lo']
9 元字符 {} 重复匹配符,重复次数由内部决定
s = re.findall('hel{1}o', 'hellllo helllo hello helo worlo') #['helo']
s = re.findall('hel{2}o', 'hellllo helllo hello helo worlo') #['hello']
s = re.findall('hel{3}o', 'hellllo helllo hello helo worlo') #['helllo']
s = re.findall('hel{1,3}o', 'hellllo helllo hello helo worlo') #['helllo', 'hello', 'helo']
10 元字符 [] 字符集,代表里面的都行,并可取消元字符功能(\ ^ - 例外)
'''常规'''
re.findall('a[bc]d', 'acd') # ['acd']
re.findall('[a-z]', 'acd') # ['a', 'c', 'd']
re.findall('[.*+]', 'a.cd+') # ['.', '+']
'''^ 在[]代表取反'''
re.findall('[^ab]','45bdha3') # ['4', '5', 'd', 'h', '3']
'''元字符之转义符\'''
re.findall('[\d]','45bdha3') #['4', '5', '3']
''' - 在[]中代表范围'''
s = re.findall('[a-z0-9A-Z]+@[a-z0-9A-Z]+.com', 'zhao@foxmail.comxo hell')
#['zhao@foxmail.com']
'''
元字符之转义符\
反斜杠后边跟元字符去除特殊功能,比如\.
反斜杠后边跟普通字符实现特殊功能,比如\d
\d 匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s 匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
\b 匹配一个特殊字符边界,比如空格 ,&,#等'''
11 元字符 | 或 两边被默认成整体
s = re.findall('wo|lo', 'hello worlo wlrlo') #['lo', 'wo', 'lo', 'lo']
s = re.findall('wo|\dr', 'hello wo8rlo wlrlo') #['wo', '8r']
s = re.findall('wo|\drr', 'hello wo8rlo wlrlo') #['wo']
12 元字符 () 分组
m = re.findall(r'(ad)+', 'add')
print(m)
ret=re.search('(?P<id>\d{2})/(?P<name>\w{3})','23/com')
print(ret.group())#23/com
print(ret.group('id'))#23
13 方法
import re
#1
re.findall('a','alvin yuan') #返回所有满足匹配条件的结果,放在列表里
#2
re.search('a','alvin yuan').group() #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
# 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
#3
re.match('a','abc').group() #同search,不过尽在字符串开始处进行匹配
#4
ret=re.split('[ab]','abcd') #先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
print(ret)#['', '', 'cd']
#5 替换,第三个参数是次数,默认全替换
ret=re.sub('\d','abc','alvin5yuan6',1)
print(ret)#alvinabcyuan6
ret=re.subn('\d','abc','alvin5yuan6')
print(ret)#('alvinabcyuanabc', 2)
#6 输出规则对象
obj=re.compile('\d{3}')
ret=obj.search('abc123eeee')
print(ret.group())#123
本文介绍了Python中正则表达式的用处、基本格式及常用元字符的使用,包括`.`、`^`、`$`、`*`、`+`、`?`、`{}`、`[]`、`|`、`()`等,通过实例演示了如何进行字符串匹配和分组操作。
8万+

被折叠的 条评论
为什么被折叠?



