python cookbook 2字符串(2)

6搜索替代文本,忽略大小寫.python

爲實現忽略大小寫,須要使用re的re.IGNORECASE標誌位正則表達式

>>> text = 'UPPER PYTHON, lower python, Mixed Python'
>>> re.findall('python', text, flags=re.IGNORECASE)
['PYTHON', 'python', 'Python']
>>> re.sub('python', 'snake', text, flags=re.IGNORECASE)
'UPPER snake, lower snake, Mixed snake'

7正則表達式最小匹配this

正則表達式默認是貪婪匹配,在正則匹配從左到右取值時,會盡可能專區知足匹配的最長字符串.編碼

當須要最小匹配時,用"?",能夠放在"*","+","?"後面
spa

貪婪匹配
>>> text2 = 'Computer says "no." Phone says "yes."'
>>> str_pat = re.compile(r'\"(.*)\"')
>>> str_pat.findall(text2)
['no." Phone says "yes.']
最小匹配
>>> str_pat = re.compile(r'\"(.*?)\"')
>>> str_pat.findall(text2)
['no.', 'yes.']

8正則表達式多重匹配code

正則表達式中"."能匹配任意字符,除了換行符
orm

>>> comment = re.compile(r'/\*(.*?)\*/')
>>> text1 = '/* this is a comment */'
>>> text2 = '''/* this is a
... multiline comment */
... '''
>>> comment.findall(text1)
[' this is a comment ']
>>> comment.findall(text2)
[]
這種狀況下,應該在正則表達式中加入換行符
>>> comment = re.compile(r'/\*((?:.|\n)*?)\*/')
>>> comment.findall(text2)
[' this is a\nmultiline comment ']
這裏(?:.|\n)定義了一個非捕捉組,若是不加?:,嵌套括號(.|\n)裏的內容也會被捕捉出來,這裏沒有匹配,捕捉爲空
>>> comment = re.compile(r'/\*((.|\n)*?)\*/')
>>> comment.findall(text2)
[(' this is a\nmultiline comment ', ' ')]
re.compile接受一個flag,re.DOTALL,能夠使"."匹配任意字符,包括換行符
>>> comment = re.compile(r'/\*(.*?)\*/', re.DOTALL)
>>> comment.findall(text2)
[' this is a\nmultiline comment ']
可是,若是你的正則表達式比較複雜,或者多個獨立的正則表達式組合到一塊兒使用,可能會出現問題,
不建議使用該flag

9將Unicode轉換爲標準形式(僅適用python3)utf-8

3.X版本中python環境就只有unicode類型的字符串了,即全部程序中處理的都會自動轉換成unicode字符串。ci

Unicode中某些字符能夠有多種有效序列
unicode

python3默認輸入是Unicode碼,輸出時會將Unicode轉換爲utf-8碼
>>> s1 = 'Spicy Jalape\u00f1o'
>>> s2 = 'Spicy Jalapen\u0303o'
>>> s1
'Spicy Jalapeño'
>>> s2
'Spicy Jalapeño'
>>> s1==s2
False
這種狀況下,對比字符串會出現問題,能夠用unicodedata進行轉換
>>> import unicodedata
>>> t1 = unicodedata.normalize('NFC', s1)
>>> t1
'Spicy Jalapeño'
>>> t2 = unicodedata.normalize('NFC', s2)
>>> t2
'Spicy Jalapeño'
>>> t1==t2
True
>>> print (t1)
Spicy Jalapeño
>>> print (ascii(t1))
'Spicy Jalape\xf1o'
>>> t3 = unicodedata.normalize('NFD', s1)
>>> t4 = unicodedata.normalize('NFD', s2)
>>> t3 == t4
True
>>> print(ascii(t3))
'Spicy Jalapen\u0303o'
normalize指明想要如何實現標準化,NFC指儘量用單個編碼符,NFD儘可能用多個編碼分解

10Unicode字符的正則表達式

>>> import re
>>> num = re.compile('\d+')
>>> num.match('123')
<_sre.SRE_Match object; span=(0, 3), match='123'>
>>> num.match('\u0661\u0662\u0663')#只有在python3中能夠實現
<_sre.SRE_Match object; span=(0, 3), match='١٢٣'>
注意一些特例,一些Unicode沒法匹配忽略大小寫
>>> pat = re.compile('stra\u00dfe', re.IGNORECASE)
>>> s = 'straße'
>>> pat.match(s)
<_sre.SRE_Match object; span=(0, 6), match='straße'>
>>> pat.match(s.upper())#不匹配
>>> s.upper()
'STRASSE'
相關文章
相關標籤/搜索