import re
pattern = re.compile(r'expression')
ma = pattern.match('string')
print (ma.group) -> result
原生字符串
pa = re.compile(r'exp')
忽略大小写
pa = re.compile(r'exp', re.I)
数据以元祖返回
pa = re.compile(r'(exp))
此时ma.groups() 元组有值
不生成pattern对象使用正则 直接使用re 适用于单次使用匹配
match = re.match(r'exp', Str)
match.group
re 的其他方法
search 在一个字符串中查找对应pattern,遇到第一个就返回match对象
str1 = 'imooc videonum=1000, likes = 999'
info = re.search('\d+', str1)
info.group()
Out:
'1000'
findall 在字符串中查找所有符合pattern的子串,返回List
str1 = 'imooc videonum=1000, likes = 999'
infoAll = re.findall(r'\d+', str1)
infoAll
Out:
['1000', '999']
sub(pattern, repl, string, count=0, flags=0) 替换
str2 = 'viewdeo num python = 90, java = 20, android = 59'
info = re.sub(r'\d+','100', str2)
info
Out:
'viewdeo num python = 90, java = 20, android = 100'
根据函数替换
repl 可以替换成有一个match对象为入参,返回参为str的函数
str2 = 'viewdeo num python = 90, java = 20, android = 59'
# 自增
def increase(ma):
val = int(ma.group())
val=val+1
return str(val)
subInfo = re.sub(r'\d+', increase, str2)
subInfo
Out:
'viewdeo num python = 91, java = 21, android = 60'