1. 程式人生 > >python 基礎 8.3 match方法和search方法

python 基礎 8.3 match方法和search方法

flags 表達式 red iter clas sub pan compile 直接

一,正則對象的split 方法 split(string[,maxsplit]) 按照能夠匹配的字串講string 分割後返回列表。maxsplit 用於指定最大分割次數,不指定將全部分割。來查找符合對象的字字符. #/usr/bin/python #coding=utf-8 #@Time :2017/11/18 20:52 #@Auther :liuzhenchuan #@File :re 的matche 和 seach.py import re print ‘正則的常用方法‘ a = re.compile(r‘\d‘) print dir(a) print ‘##‘*30 + \n
>>> 正則的常用方法 [‘__class__‘, ‘__copy__‘, ‘__deepcopy__‘, ‘__delattr__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘findall‘, ‘finditer‘, ‘flags‘, ‘groupindex‘, ‘groups‘, ‘match‘, ‘pattern‘, ‘scanner‘, ‘search‘, ‘split‘, ‘sub‘, ‘subn‘]
#1 match 方法--匹配 .match(string[,pos[,endpos]]) #string:匹配使用的文本 #pos:文本中正則比比表達式開始搜索的索引。及開始搜索 string 的下標 #endpos:文本中正則表達式結束搜索的索引 #如果不指定破損,默認從開頭匹配,如果匹配不到,直接返回None print ‘##match 匹配的應用‘ a = ‘hello world hello liu‘ #正則匹配除 hello world 與 hello liu reg = re.compile(r‘((hello w.*)(hello l.*))‘) result = reg.match(a)
print result.groups() print ‘##‘*30+ \n >>> ##match 匹配的應用 (‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘) ############################################################ print ‘##match 添加了起始位置和結束位置,match(str,2,)起始位置2,到最後結束‘ b = ‘aa‘ + a print ‘字符串b為:‘+ b result2 = reg.match(b,2,) reg = re.compile(r‘((hello w.*)(hello l.*))‘) print result2.groups() print ‘##‘*15 >>> ##match 添加了起始位置和結束位置,match(str,2,)起始位置2,到最後結束 字符串b為:aahello world hello liu (‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘) ############################## print ‘#match寫上起始位置與結束位置可以根據字符串b匹配除正則。或者用 \w 也可以匹配出‘ reg = re.compile(r‘\w*((hello w.*)(hello l.*))‘) result3 = reg.match(b) print result3.groups() print ‘##‘*30 >>> #match寫上起始位置與結束位置可以根據字符串b匹配除正則。或者用 \w 也可以匹配出 (‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘) ############################################################ #正則對象 search() 方法 這個方法用於查找字符串中可以匹配成功的字串。從string的pos 下標處嘗試匹配pattern,如果pattern結束時認可匹配,在返回一個match對象:若無法匹配,則將pos加1後重新嘗試匹配,指導pos=endpos 時仍無法匹配範虎None b = ‘aahello world hello liu‘ reg = re.compile(r‘((hello w.*)(hello l.*))‘) result4 = reg.search(b) print result4 print result4.groups() >>> <_sre.SRE_Match object at 0x037993E0> (‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘)

python 基礎 8.3 match方法和search方法