python-re模块(compile,findall:查找结果是列表,sub:替换所有符合条件的元素,serach:查找结果是一个元素 #字符串以空格为分割元素)


# ①:单独使用findall
import re
v3 = re.findall(r"html$", "https://docs.python.org/3/whatsnew/3.6.html")
v2 = re.findall(r"^http", "https://docs.python.org/3/whatsnew/3.6.html")
v1 = re.findall(r"python", "https://docs.python.org/3/whatsnew/3.6.html")
print('v3:结尾', v3)
print('v2:开头', v2)
print('v1:包含', v1)
"""
v3:结尾 ['html']
v2:开头 ['http']
v1:包含 ['python']
"""
#------------------------------------------
# ②:compile搭配findall使用
import re
#在content内容中,找到包含m的单词
content = 'Hello, I am Jerry, from jiangsu, a montain city, nice to meet you'
com = re.compile('w*mw*').findall(content)
print(com)
# ['am', 'from', 'montain', 'meet']
#------------------------------------------
#③:单独使用sub
import re
# sub第一种用法,三个参数,第一参数需要替换的数,第二个参数替换之后的参数,第三个参数是文本值
a = re.sub(r'(d+)', 'hi', 'my numer is 800 and your num is 600')
print(a)
#my numer is hi and your num is hi
#-----------------------
#④:sub结合compile使用
s = "hello 1234, goodbye, 235"
print('s:文本值', s)
# pat需要替换的内容
pat = r'd+'
m = re.compile(pat).sub('666', s)
print('m:数字替换666', m)
# s:文本值 hello 1234, goodbye, 235
# m:数字替换666 hello 666, goodbye, 666
#------------------------------
#⑤:search单独使用
import re
a = re.search('d+','2a3 1422sadf')
print(a)
#
# <re.Match object; span=(0, 1), match='2'>
#----------------------------------------
#⑥:search结合compile使用
content = 'Hello, I am Jerry, from jiangsu, a montain city, nice to meet you'
ret = re.compile('w*ow*').search(content)
print(ret.group())
print(ret)
# Hello
# <re.Match object; span=(0, 5), match='Hello'>
原文地址:https://www.cnblogs.com/12260420zxx/p/13663267.html