0
点赞
收藏
分享

微信扫一扫

python使用正则表达式案例解析


python使用正则表达式

python使用正则表达式案例解析_正则表达式

1 常用方法

  • re.match(pattern, string, flags=0)
  • re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
  • re.search(pattern, string, flags=0)
  • re.search 扫描整个字符串并返回第一个成功的匹配。
  • re.findall(pattern,string,flags=0)
  • re.findall 查找全部
  • re.sub(pattern,replace,string)
  • re.sub 替换字符串

import re


str ='I study python3.10 every_day'
print('----------------------match(规则,内容)-----------------------------') # 从头开始匹配,如果匹配上了返回值,如果匹配不上,返回none
m1 = re.match('I',str)
m2 = re.match('\w',str)
m3 = re.match('\S',str)
m4 = re.match('\D',str)
m5 = re.match('I (study)',str)
m6 = re.match('\w\s(\w*)',str)
print(m6.group(1))


print('----------------------search(规则,内容)-----------------------------') # 从任意位置开始匹配,,如果匹配上了返回值,如果匹配不上,返回none
s1 = re.search('I',str)
s2 = re.search('study',str)
s3 = re.search('p\w+',str)
s4 = re.search('p\w+.\d+',str)
print(s4.group())


print('----------------------findall(规则,内容)-----------------------------') # 从任意位置开始匹配,返回所有匹配的数据,如果没有匹配内容,返回一个空列表
f1 = re.findall('ddy',str)
print(f1)


print('----------------------sub(规则,替换的内容,内容)-----------------------------') # 替换原来的数据,并返回一个新的字符串,不会修改原来的字符串
print(re.sub('p\w+','Python',str))
print(str)


print('----------------------test()-----------------------------')
info = '<html><div><a href="http://www.itbaizhan.cn">百战程序员</a></div></html>'
tf = re.findall('<a href="(.+)">',info)
tf2 = re.findall('<a href=".+">(.+)</a>',info)
print(tf2)


举报

相关推荐

0 条评论