python中re模塊的用法

Python 的 re 模塊(Regular Expression 正則表達式)提供各種正則表達式的匹配操作,在文本解析、複雜字符串分析和信息提取時是一個非常有用的工具,下面我主要總結了re的常用方法。

1.re的簡介
    使用python的re模塊,儘管不能滿足所有複雜的匹配情況,但足夠在絕大多數情況下能夠有效地實現對複雜字符串的分析並提取出相關信息。python 會將正則表達式轉化爲字節碼,利用 C 語言的匹配引擎進行深度優先的匹配。

  1. import re
  2. print re.__doc__

    可以查詢re模塊的功能信息,下面會結合幾個例子說明。

2.re的正則表達式語法
    正則表達式語法表如下:

語法 意義 說明
"." 任意字符  
"^" 字符串開始 '^hello'匹配'helloworld'而不匹配'aaaahellobbb'
"$" 字符串結尾 與上同理
"*"  0 個或多個字符(貪婪匹配) <*>匹配<title>chinaunix</title>
"+" 1 個或多個字符(貪婪匹配 與上同理
"?" 0 個或多個字符(貪婪匹配 與上同理
*?,+?,?? 以上三個取第一個匹配結果(非貪婪匹配 <*>匹配<title>
{m,n} 對於前一個字符重複m到n次,{m}亦可 a{6}匹配6個a、a{2,4}匹配2到4個a
{m,n}? 對於前一個字符重複m到n次,並取儘可能少 ‘aaaaaa’中a{2,4}只會匹配2個
"\\" 特殊字符轉義或者特殊序列  
[] 表示一個字符集 [0-9]、[a-z]、[A-Z]、[^0]
"|" A|B,或運算
(...) 匹配括號中任意表達式  
(?#...) 註釋,可忽略  
(?=...) Matches if ... matches next, but doesn't consume the string. '(?=test)'  在hellotest中匹配hello
(?!...) Matches if ... doesn't match next. '(?!=test)'  若hello後面不爲test,匹配hello
(?<=...)  Matches if preceded by ... (must be fixed length). '(?<=hello)test'  在hellotest中匹配test
(?<!...) Matches if not preceded by ... (must be fixed length). '(?<!hello)test'  在hellotest中不匹配test

    正則表達式特殊序列表如下:

特殊序列符號 意義
\A 只在字符串開始進行匹配
\Z 只在字符串結尾進行匹配
\b 匹配位於開始或結尾的空字符串
\B 匹配不位於開始或結尾的空字符串
\d 相當於[0-9]
\D 相當於[^0-9]
\s 匹配任意空白字符:[\t\n\r\r\v]
\S 匹配任意非空白字符:[^\t\n\r\r\v]
\w 匹配任意數字和字母:[a-zA-Z0-9]
\W 匹配任意非數字和字母:[^a-zA-Z0-9]

3.re的主要功能函數
    常用的功能函數包括:compile、search、match、split、findall(finditer)、sub(subn)
compile
re.compile(pattern[, flags])
作用:把正則表達式語法轉化成正則表達式對象
flags定義包括:
re.I:忽略大小寫
re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依賴於當前環境
re.M:多行模式
re.S:’ . ’並且包括換行符在內的任意字符(注意:’ . ’不包括換行符)
re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依賴於 Unicode 字符屬性數據庫
更多用法可以在http://www.devexception.com/sitemap_index.xml上查找
search
re.search(pattern, string[, flags])
search (string[, pos[, endpos]])
作用:在字符串中查找匹配正則表達式模式的位置,返回 MatchObject 的實例,如果沒有找到匹配的位置,則返回 None。

match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函數只在字符串的開始位置嘗試匹配正則表達式,也就是隻報告從位置 0 開始的匹配情況,而 search() 函數是掃描整個字符串來查找匹配。如果想要搜索整個字符串來尋找匹配,應當用 search()。

下面是幾個例子:
例:最基本的用法,通過re.RegexObject對象調用

  1. #!/usr/bin/env python
  2. import re
  3. r1 = re.compile(r'world')
  4. if r1.match('helloworld'):
  5.     print 'match succeeds'
  6. else:
  7.     print 'match fails'
  8. if r1.search('helloworld'):
  9.     print 'search succeeds'
  10. else:
  11.     print 'search fails'

說明一下:r是raw(原始)的意思。因爲在表示字符串中有一些轉義符,如表示回車'\n'。如果要表示\表需要寫爲'\\'。但如果我就是需要表示一個'\'+'n',不用r方式要寫爲:'\\n'。但使用r方式則爲r'\n'這樣清晰多了。

例:設置flag

  1. #r2 = re.compile(r'n$', re.S)
  2. #r2 = re.compile('\n$', re.S)
  3. r2 = re.compile('World$', re.I)
  4. if r2.search('helloworld\n'):
  5.     print 'search succeeds'
  6. else:
  7.     print 'search fails'

例:直接調用

  1. if re.search(r'abc','helloaaabcdworldn'):
  2.     print 'search succeeds'
  3. else:
  4.     print 'search fails'

split
re.split(pattern, string[, maxsplit=0, flags=0])
split(string[, maxsplit=0])
作用:可以將字符串匹配正則表達式的部分割開並返回一個列表
例:簡單分析ip

  1. #!/usr/bin/env python
  2. import re
  3. r1 = re.compile('W+')
  4. print r1.split('192.168.1.1')
  5. print re.split('(W+)','192.168.1.1')
  6. print re.split('(W+)','192.168.1.1',
    1)

結果如下:
['192', '168', '1', '1']
['192', '.', '168', '.', '1', '.', '1']
['192', '.', '168.1.1']

findall
re.findall(pattern, string[, flags])
findall(string[, pos[, endpos]])
作用:在字符串中找到正則表達式所匹配的所有子串,並組成一個列表返回
例:查找[]包括的內容(貪婪和非貪婪查找)

  1. #!/usr/bin/env python
  2. import re
  3. r1 = re.compile('([.*])')
  4. print re.findall(r1,"hello[hi]heldfsdsf[iwonder]lo")
  5. r1 = re.compile('([.*?])')
  6. print re.findall(r1,"hello[hi]heldfsdsf[iwonder]lo")
  7. print re.findall('[0-9]{2}',"fdskfj1323jfkdj")
  8. print re.findall('([0-9][a-z])',"fdskfj1323jfkdj")
  9. print re.findall('(?=www)',"afdsfwwwfkdjfsdfsdwww")
  10. print re.findall('(?<=www)',"afdsfwwwfkdjfsdfsdwww")

finditer
re.finditer(pattern, string[, flags])
finditer(string[, pos[, endpos]])
說明:和 findall 類似,在字符串中找到正則表達式所匹配的所有子串,並組成一個迭代器返回。同樣 RegexObject 有:

sub
re.sub(pattern, repl, string[, count, flags])
sub(repl, string[, count=0])
說明:在字符串 string 中找到匹配正則表達式 pattern 的所有子串,用另一個字符串 repl 進行替換。如果沒有找到匹配 pattern 的串,則返回未被修改的 string。Repl 既可以是字符串也可以是一個函數。
例:

  1. #!/usr/bin/env python
  2. import re
  3. = re.compile('(one|two|three)')
  4. print p.sub('num','one word two words three words
    apple'
    , 2)

subn
re.subn(pattern, repl, string[, count, flags])
subn(repl, string[, count=0])
說明:該函數的功能和 sub() 相同,但它還返回新的字符串以及替換的次數。同樣 RegexObject 有:

另附:http://blog.csdn.net/lengyue_wy/article/details/6999310


關於正則表達式的更多信息,可以訪問:http://docs.python.org/3.2/howto/regex.html#regex-howto

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章