spock
6/11/2017 - 10:54 AM

Common regex operations.

Common regex operations.

match.group(0) # whole match
match.group(1) # first capturing group only
pat = re.compile("my_pattern", re.I)
# use regex methods on compiled pattern
pat.match(my_string)

# non-compiled eqivalence:
re.match("my_pattern", my_string, re.I)
# join multiple regex patterns
list_patterns = ['pattern1', 'pattern2', ...]
list_regexs = re.compile('|'.join(list_patterns), re.I)

# returns None if nothing found_
matchObject = re.search(pattern, input_str, flags=0)  
matchObject.group(0)  # accessing found groups
# So if you need to match at the beginning of the string, or to match the entire 
# string use match. It is faster. Otherwise use search.

matches.group('month')  # simply access named capturing group via key

matchList = re.findall(pattern, input_str, flags=0)
# same as findall, but returns iterator
matchList = re.finditer(pattern, input_str, flags=0) 

replacedString = re.sub(pattern, replacement_pattern, input_str, count, flags=0)