前言
前面兩節已經介紹了Python正則表示式的語法,接下來我們來看看 re 模組中各種函式的應用
常用函式1、Search介紹re.search(pattern, string, flags=0)
pattern: 正則匹配規則string: 目標字串flags: 匹配模式掃描整個 字串 找到匹配樣式的第一個位置,並返回一個相應的 匹配物件。
如果沒有匹配到,就返回 None ;注意這和找到一個零長度匹配是不同的。
示例ans = re.search('abc', 'abcdd')if ans: print('Search result: ', ans.group())else: print('No match')# out: Search result: abc
2、Match介紹
re.match(pattern, string, flags=0)
引數含義同上
如果 string 開始的0或者多個字元匹配到了正則表示式,就返回一個相應的 匹配物件 。
如果沒有匹配到,就返回 None ;注意它跟零長度匹配是不同的。
注意:即使在多行模式下, re.match()也只匹配字串的開始位置,而不是匹配每行開始。
如果想在 string 的任何位置搜尋,可以使用 search() 來替代
示例ans = re.match('abc', 'abcdd')if ans: print('match result: ', ans.group())else: print('No match')# out: Match result: abcans = re.match('abc', 'babcdd')if ans: print('match result: ', ans.group())else: print('No match')# out: No match
3、fullmatch介紹re.fullmatch(pattern, string, flags=0)
整個 string 都要匹配到正則表示式
匹配到就返回一個相應的 匹配物件 。否則就返回一個 None
示例ans = re.fullmatch('abc.dd', 'abcddd')if ans: print('Match result: ', ans.group())else: print('No match')# out: Match result: abcddd
4、split介紹
re.split(pattern, string, maxsplit=0, flags=0)
用 pattern 去分割 string 。
如果在 pattern 中捕獲到括號,那麼所有的組裡的文字也會包含在列表裡。
maxsplit 設定最多分隔次數, 剩下的字元全部返回到列表的最後一個元素。
示例# 用非文字字元(字母數字下劃線)分割re.split(r'\W+', 'Words, words, words.')# out: ['Words', 'words', 'words', '']# 分割字串也會保留在結果列表中re.split(r'(\W+)', 'Words, words, words.')# out: ['Words', ', ', 'words', ', ', 'words', '.', '']# 切割一次re.split(r'\W+', 'Words, words, words.', 1)# out: ['Words', 'words, words.']# 以[a-f]之間的字元分割,且不區分大小寫re.split('(?i)[a-f]+', '0a3aB9')re.split('[a-f]+', '0a3aB9', flags=re.IGNORECASE)# out: ['0', '3', '9']
5、findall介紹re.findall(pattern, string, flags=0)
從左到右進行掃描,匹配按找到的順序返回。
如果樣式裡存在一個或多個組,就返回一個組合列表
空匹配也會包含在結果裡。
前面兩節都是使用 findall ,這裡便不再舉例啦。
6、finditer介紹re.finditer(pattern, string, flags=0)
與 findall 差不多,不一樣的地方是:返回一個包含 匹配物件 的迭代器
示例for ans in re.finditer(r'\w+', 'Words, words, words.'): print(ans.group(), end='\t')# out: Words words words
7、sub介紹
re.sub(pattern, repl, string, count=0, flags=0)
使用 repl 替換 string 中匹配的子串,並返回替換後的字串。
如果樣式沒有找到,則原樣返回 string。
repl 可以是字串或函式
字串:任何反斜槓轉義序列都會被處理,如 \n 會被轉換為一個換行符,其他未知轉義序列例如 \& 會保持原樣。向後引用像是 \2 會用樣式中第 2 組所匹配到的子字串來替換。函式:那它會對每個非重複的 pattern 進行呼叫。這個函式只有一個 匹配物件 引數,並返回一個替換後的字串。可選引數 count 是要替換的最大次數,非負,預設全部匹配
示例re.sub('\w+', '123', 'hello, world, hello python')# out: '123, 123, 123 123're.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', r'static PyObject*\npy_\1(void)\n{', 'def myfunc():')# out: 'static PyObject*\npy_myfunc(void)\n{'"""pattern:匹配 Python 函式定義repl: 其中 \1 引用了捕獲的函式名 myfunc,其他原樣輸出"""def dashrepl(matchobj): if matchobj.group(0) == '-': return ' ' else: return '-' re.sub('-{1,2}', dashrepl, 'pro----gram-files')# out: 'pro--gram files'
8、subn介紹re.subn(pattern, repl, string, count=0, flags=0)
與 sub() 相同,但是返回一個元組 (字串, 替換次數).
示例re.subn('\w+', '123', 'hello, world, hello python')# out: ('123, 123, 123 123', 4)
總結
好了好了,一下子講了這麼多函式,還沒消化呢吧
今天就先講到這裡吧。
咱們明天見。