当我们在做字符串处理时,如果字符串处理函数不能实现我们想要的时,我们就借助正则来帮助我们实现了。
#coding:utf-8 import re strs = '我爱P你y你t知h吗o?n哈哈fe哈' patt = re.compile(r'^.*?(/w+).*?$',re.I) print patt.match(strs).group(1) #输出 P <?php $strs = '我爱P你y你t知h吗o?n哈哈fe哈'; preg_match('/^.*?(/w+).*?$/i',$strs,$m); var_dump($m[1]); #输出:string 'P' (length=1) preg_match('/(/w+)/',$strs,$m); patt = re.compile(r'(/w+)',re.I) print patt.search(strs).group(1) #输出 P patt = re.compile(r'/w+',re.I) for i in patt.split(strs): #注意这里要使用unicode对象输出 print unicode(i,'utf-8') #以上输出 ''' 我爱 你 你 知 吗 ? 哈哈 哈''' <?php $strs = '我爱P你y你t知h吗o?n哈哈fe哈'; $m = preg_split('//w+/i',$strs); var_dump($m); /**输出: **/ print patt.findall(strs) #输出 ['P', 'y', 't', 'h', 'o', 'n', 'fe'] <?php $strs = '我爱P你y你t知h吗o?n哈哈fe哈'; preg_match_all('/(/w+)/i',$strs,$m); var_dump($m); /** **/ for i in patt.finditer(strs): print i.group() #以上输出 ''' P y t h o n fe ''' #替换三次 print patt.sub('99',strs,3) #输出 '我爱99你99你99知h吗o?n哈哈fe哈' print patt.subn('99',strs) #输出:是一个元组('我爱99你99你99知99吗99?99哈哈99哈',7) #这里批量替换文章中的图片的路径(old_c 是文章的内容) img_dir = 'test' img_patt = re.compile('src=".*?/(/w+/./w+)"') new_c = img_patt.sub(r'src="./%s//1"'%img_dir,old_c) #这里批量替换文章中的图片的路径(old_c 是文章的内容) img_dir = 'test' img_patt = re.compile('src=".*?/(/w+/./w+)"') new_c = img_patt.sub(r'src="./%s//1"'%img_dir,old_c) #输出:
array 0 => string '我爱' (length=6) 1 => string '你' (length=3) 2 => string '你' (length=3) 3 => string '知' (length=3) 4 => string '吗' (length=3) 5 => string '?' (length=3) 6 => string '哈哈' (length=6) 7 => string '哈' (length=3)
array 0 => array 0 => string 'P' (length=1) 1 => string 'y' (length=1) 2 => string 't' (length=1) 3 => string 'h' (length=1) 4 => string 'o' (length=1) 5 => string 'n' (length=1) 6 => string 'fe' (length=2) 1 => array 0 => string 'P' (length=1) 1 => string 'y' (length=1) 2 => string 't' (length=1) 3 => string 'h' (length=1) 4 => string 'o' (length=1) 5 => string 'n' (length=1) 6 => string 'fe' (length=2)
string '我爱999你999你999知999吗999?999哈哈999哈' (length=51)