Python學習—— 正則表達式

python 正則表達式

最近開始學習python,一些基本的學習筆記,直接上代碼吧!!!`import re
print(“正則表達式”)

match方法從字符串的起上位置=開始匹配

m = re.match(“foo”,“foo”)
if m is not None:
m.group()
print( m.group())
pass

##search() 在一個字符串中查找模式(搜索與匹配的對比)
‘’’
m1 = re.match(“foo”,“seafood”) ##這是失敗的,但是foo的卻存在,下面用search 試試
if m is not None:
m1.group()
print( m1.group())
pass

sea = re.search(“foo”,“seafood”)
if sea is not None :
print( m.group()) ##搜索成功,但是匹配失敗
pass
‘’’
‘’’
##匹配多個字符串 (|)
bt = ‘bat|ber|bit’
m_bt = re.match(bt, “bat”)
if m_bt is not None:
print(m_bt.group()) # 輸出爲 bat
pass

m_bt = re.match(bt,“blt”)
if m_bt is not None:
print(m_bt.group()) # 沒有匹配
pass

m_bt= re.match(bt,“he bit me”) # 不能匹配字符串

m_bt= re.search(bt, “he bit me”) # 通過搜索查找 “bit”
‘’’

匹配任何字符 (.)

anyend = ‘.end’
m_anyend = re.match(anyend,‘bend’)
if m_anyend is not None:
print(m_anyend.group()); #點號匹配 b 輸入爲bend
pass

m_anyend1 = re.match(anyend,‘end’)
if m_anyend1 is not None:
print(m_anyend1.group()); # 不匹配任何字符
pass

m_anyend2 = re.match(anyend,’\nend’)
if m_anyend2 is not None:
print(m_anyend2.group()); # 除了\n之外的任何字符
pass

m_anyend3 = re.search(’…end’, ‘the LJend’)
if m_anyend3 is not None:
print(m_anyend3.group()); # 在搜索中匹配”LJ“ 打印 LJend
pass

‘’’
1.3.8 創建字符集
r2d2|c3po 與 [cr][23][dp][o2] 比較
2018.12.22
‘’’

m_str1 = re.match(’[cr][23][dp][o2]’,‘ssda r3p2’) #匹配r3p2
if m_str1 is not None:
print(m_str1.group())
pass
m_str2 = re.match(‘r2d2|c3po’, ‘c2do’) #不能匹配
if m_str2 is not None:
print(m_str2.group())
pass

m_str3= re.match(‘r2d2|c3po’ , ‘c3po’) #匹配 r2d2 或者 c3po
if m_str3 is not None:
print(m_str3.group())
pass

‘’’
1.3.9 重複。特殊字符及分組
\w+@(w+)?\w+.com
2018.12.22
‘’’
m_patt = ‘\w+@(\w+,)?\w+.com’ # 允許.com前面又一個或者兩個的名稱
m_str4 = re.match(m_patt, ‘[email protected]’)
if m_str4 is not None:
print(m_str4.group())
pass

m_str5 = re.match(m_patt, ‘[email protected]’)
if m_str5 is not None:
print(m_str5.group())
pass

m_patt1 = ‘\w+@(\w+,)*\w+.com
m_str6 = re.match(m_patt1, ‘[email protected]’)
if m_str6 is not None:
print(m_str6.group())
pass

‘’’
1.3.10 匹配字符串的起始和結尾及單詞的邊界
2018.12.22
‘’’
m_str1_3_10 = re.search(’^the’, ‘the end’) # 匹配the
if m_str1_3_10 is not None:
print(m_str1_3_10.group())
pass

m_str1_3_10_1 = re.search(’^the’, ‘end. the’) # 不能匹配 不作爲起始
if m_str1_3_10_1 is not None:
print(m_str1_3_10_1.group())
pass

m_str1_3_10_2 = re.search(r’\bthe’, ‘bitethe dog’ ) #有邊界
if m_str1_3_10_2 is not None:
print(m_str1_3_10_2.group())
pass

m_str1_3_10_2 = re.search(r’\Bthe’, ‘bitethe dog’ ) #無邊界
if m_str1_3_10_2 is not None:
print(m_str1_3_10_2.group())
pass
`

發佈了37 篇原創文章 · 獲贊 11 · 訪問量 9164
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章