re . 匹配除換行符之外的任意字符 \w 匹配字母或數字或下劃線或漢字 \s 匹配任意的空白符 \d 匹配數字 \b 匹配單詞的開始或結束 ^ 匹配字符串的開始 $ 匹配字符串的結束 * 重複零次或更屢次 + 重複一次或更屢次 ? 重複零次或一次 {n} 重複n次 {n,} 重複n次或更屢次 {n,m} 重複n到m次 # import re # match # print(re.match('com', 'comwww.runcombb').group()) # match 匹配起始位置 # print(re.search('com', 'www.runcombb').group()) # search 匹配第一次位置 # sub subn 匹配 替換 # print(re.sub("g.t", "have", 'I get A, get B', 1)) # 1表示只替換1次 # print(re.subn("g.t", "have", 'I get A, get B')) # 提示替換了幾回 # split # print(re.split('\d+', 'one1two2three3four4')) # 有空格 # 輸出 # ['one', 'two', 'three', 'four', ''] # compile 封裝一個固定匹配規則供屢次調用 # s = "JGood is a boy,so cool..." # r = re.compile(r'\w*oo\w*') # 查找全部包含oo的單詞 # print(r.findall(s)) # 輸出: # ['JGood', 'cool'] # 反斜槓 # 在Python中 要進行兩次轉義才能匹配一個帶反斜槓的字符 因此須要4個 \\\\ # print(re.search("\\\\com", "\comcn").group()) # 單詞 # print(re.findall(r'I\b', 'I&am Ikobe')) # 有不少字符能夠用來分隔單詞 這裏使用& # 分組 # 去已經匹配到的數據中再提取數據 # origin = 'has sdfsdfsdfwer432' # r = re.match("h\w+", origin) # 輸出:has () {} # r = re.match("h(\w+)", origin) # 輸出:has ('as',) {} # r = re.match("h(?P<name>\w+)", origin) # 輸出:has ('as',) {'name': 'as'} # print(r.group()) # print(r.groups()) # print(r.groupdict()) # findall 分組 # origin = "hasaabc halaaabc" # r = re.findall("h(\w+)a(ab)c", origin) # 首先總體匹配 再將分組放入結果 # print(r) # 輸出: # [('as', 'ab'), ('ala', 'ab')] # spilt 分組 # origin = "hello alex abc alex age" # r = re.split("a(le)x", origin, 1) # 忽略了alex 直接匹配le # print(r) # 輸出: # ['hello ', 'le', ' abc alex age']