正則表達式中字符含義:
預定義字符集 | |
---|---|
\d | 數字:[0-9] |
\D | 非數字:[^\d] |
\s | 空白字符:[\t\f\r\v\n] |
\S | 非空白字符:[^\s] |
\w | 單詞字符:[A-Za-z0-9_] |
\D | 非單詞字符:[^\w] |
數量詞(用在字符或者(…)之後) | |
---|---|
* | 匹配前一個字符0次或者無限次 |
+ | 匹配前一個字符1次或者無限次 |
? | 匹配前一個字符0次或者1次 |
{m} | 匹配前一個字符m次 |
{m,n} | 匹配前一個字符m次至n次,如果m省略,即0~n次,如果n省略,即m~無限次 |
使用正則表達式來匹配字符:
匹配單個字符:
當正則表達式中不帶括號時,列表的元素爲字符串,此字符串爲整個正則表達式匹配的內容
import re
str="this is an example"
re1=re.compile('\w')
re1.findall(str)
['t', 'h', 'i', 's', 'i', 's', 'a', 'n', 'e', 'x', 'a', 'm', 'p', 'l', 'e']
匹配單詞:
re1=re.compile('\w+') #不帶空格
re1.findall(str)
['this', 'is', 'an', 'example']
re1=re.compile('\w+\s') #帶有空格
re1.findall(str)
['this ', 'is ', 'an ']
re1=re.compile('\w+\s+\w+') #字符空格字符
re1.findall(str)
['this is', 'an example']
當正則表達式中帶有一個括號時,列表的元素爲字符串,次字符串的內容與括號中的正則表達式相對應(不是整個表達式的匹配內容)
re1=re.compile('(\w+)\s+\w+')
re1.findall(str)
['this', 'an']
當正則表達式中帶有多個括號時,列表的元素爲多個字符串組成的tuple,tuple中的字符串個數與括號對數相同,字符串內容與每個括號內的正則表達式相對應,並且排放順序是按括號出現的順序。
re1=re.compile('((\w+)\s+\w+)')
re1.findall(str)
[('this is', 'this'), ('an example', 'an')]
參考博客:http://blog.csdn.net/drdairen/article/details/51134816[感謝博主]