re庫是python的標準庫,主要用於字符串匹配。
Re庫主要功能函數python
re.search()函數正則表達式
re.match()函數函數
import re line = 'hello 123' # ^h表示以h開頭,.表示任意字符,*表示任意屢次 re_str = '^h.*' if re.match(re_str, line): print('匹配成功') # 輸出:匹配成功
import re line = 'hello 123' re_str = '.*3$' # 前面可爲任意多個任意字符,但結尾必須是3 if re.match(re_str, line): print('匹配成功') # 輸出:匹配成功
import re line = 'heeeello123' re_str = '.*?(h.*?l).*' # 只要()中的子串 match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) # 輸出:heeeel # 若是去掉?,則輸出:heeeell
import re line = 'heeeello123' re_str = '.*(h.+?l).*' match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) #輸出:heeeel
import re line = 'heeeello123' re_str = '.*?(e.{2}?l).*' # 匹配的是e+任意2個字符+l match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) # 輸出:eeel
import re line = 'hello123' re_str = '((hello|heeello)123)' match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) # 輸出:python123
import re line = 'hello123' re_str = "([jhk]ello123)" # [jhk]表示jhk中的任一個均可以 match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) # 輸出:hello123
import re line = 'hello123' re_str = "([^j]ello123)" # [^j]表示不是j的都行 match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) # 輸出:hello123
import re line = 'hello123 好' #字符串有空格 re_str = "(hello123\s好)" # 匹配上空格 match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) #輸出:hello123 好
import re line = 'hello 北京大學' re_str = ".*?([\u4E00-\u9FA5]+大學)" match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1)) # 輸出:北京大學
import re line = 'xxx出生於2000年6月1日' line = 'xxx出生於2000/6/1' line = 'xxx出生於2000-6-1' line = 'xxx出生於2000-06-01' line = 'xxx出生於2000-06' re_str = ".*出生於(\d{4}[年/-]\d{1,2}([月/-]|\d{1,2}|$))" match_obj = re.match(re_str, line) if match_obj: print(match_obj.group(1))