1. 程式人生 > >Python re 模組以及正則表示式

Python re 模組以及正則表示式

re.compile( ):將正則表示式編譯成一個物件,加快速度並可以重複使用。

import re
re.complie()

re.sub() :對字串做替換處理

'''
 re.sub(pattern, repl, string, count=0, flags=0)
'''
test  = "今天是我的18歲生日,我收到1份價值10萬的禮物。"
pattren = re.compile('[\u4e00-\u9fa5]')
print(pattern.sub("", test))

output: 18110

常用的幾個正則表示式:

\d 匹配一個數字
\d{3} 匹配3個數字,如‘010’
\w 匹配一個數字或者字母
[\u4e00-\u9fa5] 匹配一箇中文
^ 行的開頭,^\d 必須以數字開頭
$ 行的結尾

同時可以將正則使用在split中:

>>> test= 'a b    c  d'
>>> test.split(' ')
['a', 'b', '', '', '', 'c', '', 'd']

'''針對不規範的使用者輸入,巧用正則化'''

>>> re.split("\s+",test)
['a', 'b', 'c', 'd']

>>> test= 'a b,    c; d'
>>> re.split("[\s,;]+",test) ['a', 'b', 'c', 'd']