BZ易风

导航

 

语法

 

 

在DOTALL模式中能匹配到换行

常用正则表达式的方法:

re.compile(编译)
pattern.match(从头找一个)
pattern.search(找一个)
pattern.findall(找所有)
pattern.sub(替换)

import re

str = "yi333feng9"
# re.sub(正则, 替换后的字符, 字符串)  替换
print(re.sub("\d+", "_", str))  # yi_feng_
# 定位和过滤
print(re.findall("i(.*?)g", str))  # 能够返回括号中的内容,括号前后的内容起到定位和过滤的效果  # ['333fen']
# re.compile()  编译
p = re.compile("\d")  # re.compile("\d", re.UNICODE)
print(p.findall(str))  # 相当于 re.findall("\d", str)  ['3', '3', '3', '9']
# 如果想用DOTALL模式,要写在编译里面才能用
p = re.compile(".", re.S)
print(p.findall("\n"))  # ['\n']
# 如果编译里没写DATALL模式的话,后面再用就匹配不到了
p = re.compile(".")
print(p.findall("\n", re.S))  # []

# 原始字符串r的用法
print(re.findall(r"a\nb", 'a\nb'))  # ['a\nb']  加上r""能忽略转移符号
print(re.findall(r"a\nb", 'a\\nb'))  # []

 

posted on 2019-10-24 17:02  BZ易风  阅读(158)  评论(0编辑  收藏  举报