模塊的的作用主要是用于字符串和文本處理,查找,搜索,替換等
復習一下基本的正則表達式吧
.:匹配除了換行符以為的任意單個字符
*:匹配任意字符,一個,零個,多個都能匹配得到 俗稱貪婪模式
+:匹配位于+之前的一個或者多個字符
|:匹配位于|之前或者之后的字符
^:匹配行首
$:匹配行尾
?:匹配位于?之前的零個或者一個字符,不匹配多個字符
/:表示 / 之后的為轉義字符
[]:匹配[]之中的任意單個字符,[0-9]表示匹配0到9任意一個數字
():將位于()之內的的內容當作一個整體
{}:按{}中的次數進行匹配,100[0-9]{3}表示在100之后任意匹配一個3位數(100-999)
python中以/開頭的元字符:
| 特殊序列符號 | 意義 |
| /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] |
正則表達式語法表
| 語法 | 意義 | 說明 |
| "." | 任意字符 | |
| "^" | 字符串開始 | '^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個 |
| "http://" | 特殊字符轉義或者特殊序列 | |
| [] | 表示一個字符集 | [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 |
匹配的標志和含義
| 標志 | 含義 |
| re.I | 忽略大小寫 |
| re.L | 根據本地設置而更改/w,/W,/b,/B,/s,/S的匹配內容 |
| re.M | 多行匹配模式 |
| re.S | 使“.”元字符匹配換行符 |
| re.U | 匹配Unicode字符 |
| re.X | 忽略需要匹配模式中的空格,并且可以使用"#"號注釋 |
文本內容(提取Linux下的password文件)
man:x:6:12:man:/var/cache/man:/bin/nologin
re模塊中有3個搜索函數,每個函數都接受3個參數(匹配模式,要匹配的字符串,進行匹配的標志),如果匹配到了就返回一個對象實例,么有就返會None.
findall():用于在字符串中查找符合正則表達式的字符串,并返回這些字符串的列表
search():搜索整個字符串,返回對象實例
match():只從第一個字符開始匹配,后面的不再匹配,返回對象實例
lovelinux@LoveLinux:~/py/boke$ cat text man:x:6:12:man:/var/cache/man:/bin/shlovelinux@LoveLinux:~/py/boke$ cat test.py#/usr/bin/env python#coding:utf-8import rewith open('text','r') as txt: f = txt.read() print re.match('bin',f) print re.search('bin',f).end() lovelinux@LoveLinux:~/py/boke$ python test.py None34lovelinux@LoveLinux:~/py/boke$ vim test.pylovelinux@LoveLinux:~/py/boke$ python test.py None<_sre.SRE_Match object at 0x7f12fc9f9ed0>返回是對象實例有2個方法,
start():返回記錄匹配到字符的開始索引
end():返回記錄匹配到字符的結束索引
lovelinux@LoveLinux:~/py/boke$ python test.py None3134lovelinux@LoveLinux:~/py/boke$ cat test.py #/usr/bin/env python#coding:utf-8import rewith open('text','r') as txt: f = txt.read() print re.match('bin',f) print re.search('bin',f).start() print re.search('bin',f).end()新聞熱點
疑難解答
圖片精選