# -*- coding:utf-8 -*- # re模塊是python中內置的用啦支持正則表達式的模塊 import re string = 'hello world' # 1.準備正則 pattern = re.compile('ello') # 2.使用正則表達式,從大字符串中搜索小字符串 # match(正則表達式, 要進行查找的大字符串) # match() 如果找到結果,返回結果對象,沒找到返回None # match() 要查找的子串必須位於大字符串中開頭位置纔可以匹配成功,如果不在匹配失敗,返回None res = re.match(pattern, string) if res: # group() 用來獲取分組信息,分組信息在complie()正則表達式中設置 print(res.group()) else: print('沒有匹配到數據') # search(正則表達式, 要進行查找的大字符串) # search() 如果找到結果,返回結果對象,沒找到返回None # search() 要查找的子串可以位於大字符串中的任意位置,如果不在匹配失敗,返回None res = re.search(pattern, string) if res: print(res.group()) else: print('沒有匹配到數據') # ------------------------------------------------- string2 = 'abcccbccdef' # .匹配任意字符 *匹配前一個字符0次或無限次 # 默認.*是貪婪模式 儘可能多的匹配數據 pattern = re.compile('a.*b') res = re.search(pattern, string2) if res: print(res.group()) else: print('沒有匹配到數據') # ------------------------------------------------- # 一般使用的都是非貪婪模式,儘可能少的取做數據的匹配 # .*? 非貪婪模式 pattern = re.compile('a.*?b') res = re.search(pattern, string2) if res: print(res.group()) else: print('沒有匹配到數據') # ------------------------------------------------- # +表示匹配前一個字符1次或無限次 .+?非貪婪模式 pattern = re.compile('a.+?b') res = re.search(pattern, string2) if res: print(res.group()) else: print('沒有匹配到數據') # ------------------------------------------------- # | 表示或者,兩邊的正則符合一個即可 pattern = re.compile('a.*?b|c.*?b') res = re.search(pattern, string2) if res: print(res.group()) else: print('沒有匹配到數據')
基於python的-正則表達式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.