字符串的搜索旨椒、匹配以及特殊字符的處理
-
忽略大小寫搜索與替換文本
直接給re模塊中函數(shù)添加re.IGNORECAS
參數(shù)互站,re.I
為縮寫形式
import re
str1="UPPER PYTHON, lower python, Mixed Python"
compilelist=re.findall("python",str1,flags=re.IGNORECASE)
print(compilelist)#結(jié)果:['PYTHON', 'python', 'Python']
-
多行匹配模式
通常出現(xiàn)在模式文本的內(nèi)容跨越了多行廉丽,示例:獲取/**/直接的文本
text1='''/* this is a
multiline comment */
'''
text2="/* this is amultiline comment */"
pattern= re.compile(r'/\*(.*?)\*/')
compiletext1=pattern.findall(text1)#結(jié)果[]
compiletext2=pattern.findall(text2)結(jié)果['this is amultiline comment']
print(compiletext1)
解決方法
?? a. 正則表達(dá)式中加上\n
?? b. re模塊中函數(shù)添加,re.DOTALL
參數(shù)
#方法2
text='''/* this is a
multiline comment */
'''
pattern= re.compile(r'/\*(.*?)\*/',re.DOTALL)
compiletext=pattern.findall(text)
print(compiletext)#結(jié)果:[' this is a\nmultiline comment ']
#方法1
pattern1= re.compile(r'/\*((?:.|\n)*?)\*/',re.DOTALL)#(?:.|\n)指定為非捕獲組职烧,僅僅用來做匹配貌踏,無組的概念
compiletext1=pattern.findall(text)
print(compiletext1)#結(jié)果:[' this is a\nmultiline comment ']
-
最短匹配
當(dāng)使用正則表達(dá)式去匹配某個(gè)文本十气,有可能找到的為模式的最長匹配
概念
?? 正則表達(dá)式的貪婪模式和非貪婪模式
?? Python中使用正則表達(dá)式捕捂,默認(rèn)為貪婪模式瑟枫,即盡量匹配可能的最長文本,如果想要匹配最短文本指攒,需要將貪婪模式變成非貪婪模式慷妙,即在被量詞(*或+等)前面加上? ,尋找最短的可能匹配允悦。通俗地說膝擂,貪婪模式有多少可匹配的取多少,非貪婪模式隙弛,找到就好了
import re
text='Computer says "no." Phone says "yes."'
pattern1=re.compile(r"\"(.*)\"")#貪婪模式
pattern2=re.compile(r"\"(.*?)\"")#非貪婪模式
compiledText1=pattern1.findall(text)
compiledText2=pattern2.findall(text)
print(compiledText1)#結(jié)果['no." Phone says "yes.']
print(compiledText2)#結(jié)果['no.', 'yes.']
-
刪除字符串開始或者結(jié)尾多余處的字符
使用字符串方法
strip() 刪除開始和結(jié)尾的指定字符架馋,默認(rèn)是空格
lstrip() 刪除開始的指定字符,默認(rèn)是空格
rstrip() 刪除結(jié)尾的指定字符全闷,默認(rèn)是空格
text=" we are === ---- "
text_all=text.strip()
text_right=text.rstrip()
text_left=text.lstrip()
text_other=text.rstrip("= - ")#可指定多個(gè)
#結(jié)果
#原始字符串:測(cè)試 we are === 結(jié)果
#原始字符串:測(cè)試 we are === ---- 結(jié)果
#去掉開始和結(jié)尾空格:測(cè)試we are === ----結(jié)果
#去掉結(jié)尾空格:測(cè)試 we are === ----結(jié)果
#去掉開始空格:測(cè)試we are === ---- 結(jié)果
#去掉結(jié)尾空格:測(cè)試 we are結(jié)果
期待后續(xù)