CodyKochmann
4/16/2017 - 4:01 PM

group a list of strings based on a specified regex in python

group a list of strings based on a specified regex in python

from re import search, findall

def group_strings(string_iterable, pattern_to_group_with):
    """ groups strings based on a given regex and returns the groups in a dict
        by: Cody Kochmann """
    groups={}
    for i in string_iterable:
        if search(pattern_to_group_with, i):
            group = findall(pattern_to_group_with, i)[0]
            if group in groups:
                groups[group].append(i)
            else:
                groups[group]=[i]
    return groups