40 python 正則表達式 match方法匹配字符串 使用search函數在一個字符串中查找子字

第一課: 使用match方法匹配字符串 # 正則表達式:使用match方法匹配字符串 ''' 正則表達式:是用來處理文本的,將一組類似的字符串進行抽象,形成的文本模式字符串 windows dir *.txt file1.txt file2.txt abc.txt test.doc a-file1.txt-b linux/mac ls 主要是學會正則表達式的5方面的方法 1. match:檢測字符串是否匹配正則表達式 2. search:在一個長的字符串中搜索匹配正則表達式的子字符串 3. findall:查找字符串 4. sub和subn:搜索和替換 5. split: 通過正則表達式指定分隔符,通過這個分隔符將字符串拆分 ''' import re # 導入正則表達的模塊的 m = re.match('hello', 'hello') # 第一個指定正則表達式的字符串,第二個表示待匹配的字符串 實際上 正則表達式也可以是一個簡單的字符串 print(m) # <re.Match object; span=(0, 5), match='hello'> print(m.__class__.__name__) # 看一下m的類型 Match print(type(m)) # <class 're.Match'> m = re.match('hello', 'world') if m is not None: print('匹配成功') else: print('匹配不成功') # 待匹配的字符串的包含的話正則表達式,系統也認爲是不匹配的 m = re.match('hello', 'world hello') print(m) # None 如果不匹配的話,返回值爲None # 待匹配的字符串的前綴可以匹配正則表達式,系統也認爲是匹配的 m = re.match('hello', 'hello world') print(m) # <re.Match object; span=(0, 5), match='hello'> ---------------------------------------------- 第二課 正則中使用search函數在一個字符串中查找子字符串 # search函數 和 match函數的區別是,search函數中 字符串存在就可以匹配到,match函數 必須要 前綴可以匹配正則表達式,系統也認爲是匹配的 import re m = re.match('python', 'I love python.') if m is not None: print(m.group()) # 調用group的方法就是返回到一個組裏面 print(m) # None m = re.search('python', 'I love python.') if m is not None: print(m.group()) print(m) # # python # <re.Match object; span=(7, 13), match='python'> span=(7, 13) 表示 python在 'I love python.' 字符串中的位置 左閉右開
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章