文字列処理を行うときに、文字列処理関数で目的を達成できない場合は、正規表現を使用して目的を達成します。
正規表現が使用される一般的な状況には、マッチング、検索、セグメント化、検索、置換が含まれます。以下では、これらの状況をそれぞれ PHP と Python で実装し、比較します。
通常の PHP は PCRE スタイルを採用しています。
#1 Match Math (そして結果を取得)(ここでは一致結果を取得する必要があります。これは結果を取得しないこととは異なります)
Python:
#coding:utf-8 import re strs = '私はあなたを愛しています。ははは、フェハ パット = re.コンパイル( r'^.*?(w+).*?$',re. 私) print patt.match( strs ).group(1) #Output P
match の機能は検索ではなく照合プロセスであることを説明します。この方法は完全一致ではありません。完全一致が必要な場合は、式の最後に境界一致文字「$」を追加できます。
PHP:
936f9eaf97f9451f933c9bb67cf2cf8c 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)
**/
#4 搜索查找所有结果(ALL)
Python:
print patt.findall(strs) #输出 ['P', 'y', 't', 'h', 'o', 'n', 'fe']
在PHP中可使用preg_match_all() 来实现
PHP:
8254804cc93b9d330b3fdf11f1ac5607 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)
**/
#5 查找替换
实际上finditer()方法在python中不是查找替换,它仅是返回一个顺序访问每一个匹配结果(Match对象)的迭代器
python:
for i in patt.finditer(strs): print i.group() #以上输出 ''' P y t h o n fe '''
这和PHP中的preg_filter()有所不同,preg_filter()与preg_replace()都是执行一个正则表达式的搜索和替换。在python中正则方法中,用于查找替换的是:sub()与subn()。需要注意的是sub()返回的一个新字符串,不是作用在原对象上。
subn()返回的是一个以“新字符串和替换的次数”组成的元组,也没有作用到原对象上。
#替换三次 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)
PHP:
#这里批量替换文章中的图片的路径(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)
#输出:
<span class="com" style="color: rgb(136, 0, 0);">string</span><span class="com" style="line-height: 25px; color: rgb(136, 0, 0);"> </span><span class="com" style="color: rgb(136, 0, 0);">'我爱999你999你999知999吗999?999哈哈999哈'</span><span class="com" style="line-height: 25px; color: rgb(136, 0, 0);"> </span><i style="line-height: 25px;"><span class="com" style="color: rgb(136, 0, 0);">(length=51)</span></i>
另注 1 对于正则的基础知识可以GOOGLE一下,Python正则的基础知识也可以GOOGLE一下。
2 对于更多关于PHP PCRE风格的正则基础,可以参看:http://cn2.php.net/manual/zh/regexp.introduction.php
3 另外有一点需要注意的是:对于处理字符串能用字符串函数处理的就用函数处理,千万别用正则。