re模块正则常用方法

image.png

image.png

image.png

image.png

image.png

image.png
#coding:utf-8
import paramiko
import time
import codecs
import linecache
import re
import ftplib
#match 和 search 是匹配一次 findall 匹配所有
txt='''一、go 77 for it! just do it! 加油__!向前冲!做了再说!
二、better late than never. 只要开始&&,虽晚不迟。127.0.0.1'''

pattern1=re.compile("\S.*加油")
pattern2=re.compile("\w.*&",re.S)
cc1=re.match(pattern2,txt).group(0) #从开头匹配
print(cc1)
pattern3=re.compile("\d.*do")
cc2=re.search(pattern3,txt).group(0)#任意位置匹配
print(cc2)
pattern4=re.compile("\d{3}.\d{1}.\d{1}.\d{1}")
cc3=re.findall(pattern4,txt)#匹配任意字段返回list
print(cc3)
print(re.match("[0-35-9]Hello world","2Hello world").group())
print(re.findall("\w{1}.\w{2}.\w{1}","b,zz,A"))
print(re.findall("A{1,3}","A,AAA,A is Apple,I like AAAples"))
print(re.findall("[A-Za-z_]+\w","7_name_ _")) #匹配[]中列举的字符
print(re.findall("n(.*)\S","7_name_ _"))
print(re.findall("\d+","apple123456,banana988777,pear877666"))#findall匹配所有
print(re.sub("\d+","888abc","apple12345,banana988777,pear877666"))#sub替换匹配的数据
print(re.split(":|,","name:lili,age:18,score:99"))#字符串分割,|匹配左右任意一个表达式


#打印结果
一、go 77 for it! just do it! 加油__!向前冲!做了再说!
二、better late than never. 只要开始&&
77 for it! just do
['127.0.0.1']
2Hello world
['b,zz,A']
['A', 'AAA', 'A', 'A', 'AAA']
['_name_']
['ame_ ']
['123456', '988777', '877666']
apple888abc,banana888abc,pear888abc
['name', 'lili', 'age', '18', 'score', '99']

你可能感兴趣的:(re模块正则常用方法)