標準庫模塊:re 正則表達式
阿新 • • 發佈:2018-05-11
分隔 dota group () find ear multi lag pro
1 ‘.‘ 默認匹配除\n之外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行 2 ‘^‘ 匹配字符開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) 3 ‘$‘ 匹配字符結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以 4 ‘*‘ 匹配*號前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 結果為[‘abb‘, ‘ab‘, ‘a‘] 5 ‘+‘ 匹配前一個字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果[‘ab‘, ‘abb‘] 6 ‘?‘ 匹配前一個字符1次或0次 7 ‘{m}‘ 匹配前一個字符m次 8 ‘{n,m}‘ 匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果‘abb‘, ‘ab‘, ‘abb‘] 9 ‘|‘ 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結果‘ABC‘ 10 ‘(...)‘ 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c 11 12 13 ‘\A‘ 只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的 14 ‘\Z‘ 匹配字符結尾,同$ 15 ‘\d‘ 匹配數字0-9 16 ‘\D‘ 匹配非數字 17 ‘\w‘ 匹配[A-Za-z0-9] 18 ‘\W‘ 匹配非[A-Za-z0-9] 19 ‘\s‘ 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 ‘\t‘ 20 21 ‘(?P<name>...)‘ 分組匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 結果{‘province‘: ‘3714‘, ‘city‘: ‘81‘, ‘birthday‘: ‘1993‘}
匹配語法
re.match 從頭開始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符當做列表分隔符
re.sub 匹配字符並替換
標準庫模塊:re 正則表達式