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
`