標籤:python Regex
python Regex
re 模組
分析日誌,提取資訊
一般字元
原字元:
. 代表任意一個字元
^ 以什麼開頭 , ^[abc]表示以abc開頭
$ 以什麼結尾
* 匹配前面的字元或運算式0次或多次 0,1,2 ……
+ 匹配前面字元或運算式至少1次 1,2,3 ……
? 匹配前面字元或運算式0次或1次 0,1
{} 裡面可以是數值,{123}作為一個整體,可以匹配該整體幾次
[] 匹配裡面的某個字元,裡面可以是個集合[0-9,a-z]
\ 轉意,\$,表示就是 $
| 表示或
() 表示分組
Regex
\d 匹配任何十進位數,相當於[0-9]
\D 匹配任何非十進位數,相當於[^0-9]
\s 匹配任何空白字元,相當於[\t\n\r\f\v]
\S 匹配任何非空白字元,相當於[^\t\n\r\f\v]
\w 匹配任何字母和數字,相當於[a-zA-Z0-9]
\W 匹配任何非字母數字字元,相當於[^a-zA-Z0-9]
pattern:Regex,string:字串 flag:標記,預設是0,返回的是一個列表In [1]: import reIn [2]: help(re.findall)Help on function findall in module re:findall(pattern, string, flags=0) Return a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. In [1]: import reIn [2]: help(re.findall)In [3]: re.findall(r‘^ab+‘, ‘asdabbbb‘) #匹配以ab開頭的行,沒有找到Out[3]: []In [4]: re.findall(r‘ab+‘, ‘asdabbbb‘) #匹配包含ab,b可以有多個,匹配到abbbbOut[4]: [‘abbbb‘]In [5]: re.findall(r‘^ab+‘, ‘absdabbbb‘) #匹配以ab開頭的字元,abOut[5]: [‘ab‘]In [6]: re.findall(r‘ab+‘, ‘absdabbbb‘) #匹配包含字元ab,匹配結果ab,abbbbOut[6]: [‘ab‘, ‘abbbb‘]
本文出自 “梅花香自苦寒來!” 部落格,請務必保留此出處http://daixuan.blog.51cto.com/5426657/1887003
python Regex