Python Regex Cheat Sheet

Function Behavior Example re.match(pattern, string, flags=0) Match only at start re.match(r’\d+’, ‘123abc’) re.search(pattern, string, flags=0) Match anywhere in string re.search(r’\d+’, ‘abc123def’) re.findall(pattern, string, flags=0) Returns all matches as list re.findall(r’\d+’, ’12, 34′) → [’12’,’34’] re.finditer(pattern, string, flags=0) Returns iterator of Match objects for m in re.finditer(r’\d+’, ’12, 34′): print(m.group()) re.sub(pattern, repl, string, count=0, flags=0) Replace matches with repl re.sub(r’\d+’, ‘#’, ‘a1b2’) → ‘a#b#’ re.subn(pattern, repl, string, count=0, flags=0) Same as sub + returns tuple (new_string, num_subs) re.subn(r’\d+’, ‘#’, ‘a1b2’) → (‘a#b#’, 2) re.split(pattern, string, maxsplit=0, flags=0) Split string on regex matches re.split(r’\s+’, ‘a b c’) → [‘a’,’b’,’c’]

Read more here: Source link