TOP

python-day23(正则表达式,RE)

一. 正则表达式

  元字符

  .   匹配出换行符以外的所有字符

  \w匹配数字  字母  下划线

  \s 匹配 空白符

  \b单词的末尾

  \d 匹配数字

  \W  非 数字 字母 下划线

  \D  非数字

  \S 非空白符

  ^ 开头

  $ 结尾

  [ ] 字符组

  [ ^ ] 除了字符组中的元素外

  量词 限定符

  *  {0,n}

  + {1,n}

  ? 零或一

  {n} n次

  {p,} p,或更多

  {n,m} n-m次

  贪婪匹配: * + {} 尽可能的多匹配结果

  .*  匹配除换行符

  .+ 

  ----------

  分组()

# 这个分组是优先级
lst = re.findall(r"www\.(baidu|oldboy)\.com","www.oldboy.com")
print(lst)

#(?: ) 去掉优先级
lst = re.findall(r"www\.(?:baidu|oldboy)\.com","www.oldboy.com")
print(lst)

 

  转义 \ 

  \n  换行

  \\n  \n

  \ .  转义

  \ /转义

  \ ?转义

 

二. re模块  

  findall() 获取到匹配的所有内容

lst = re.findall('\w+','alex and exo')
print(lst)

  finditer() 匹配到所有内容  返回迭代器

it = re.finditer('\w+','mai l fo leng ') #返回的迭代器
for el in it:
    print(el.group())

  search()  搜索. 查到了就返回

res = re.search('e','eeeeaassd') #搜索,搜到结果就返回
print(res.group())

  match()  匹配. 从头开始匹配

res = re.match('\w+','alex is not a good man')#从头匹配,如果匹配到了就返回
print(res.group())

  r"(?P<name>正则)"

 其他

  

# 替换
ret = re.sub(r"\d+","_sb_","alex333wusir333")
print(ret)

#替换,返回的结果带有次数
res = re.subn(r"\d+","_sb_","alex333wusir333")
print(res)
obj = re.compile(r'alex(?P<name>\d+)and') #把正则表达式预加载
res = obj.search('alex250andwusir38ritian2')
print(res.group())
print(res.group('name'))

res = re.search(r'a(?P<name>\d)','a1wsdweq1qaqa2')
print(res.group())
print(res.group('name'))

 

posted on 2018-11-16 20:54  hui_T  阅读(199)  评论(0编辑  收藏  举报