Return a dictionary of Regex Matches

An example of how to make your function more flexible to handle a different number of return values. This means you won’t have to write the same code repeatedly if you are only changing the number of groups that are being returned.

def findMatches(string, regex) -> dict:
    """
    This is a generic matching function.
    Warning! Your regex expression MUST use 'Named Groups' -> (:P<name>) or
    this function will return an empty dictionary
    
    :param string: The text you are searching
    :type string: str
    :param regex: The regular expression string you are using to search
    :type regex: str
    :returns: A dictionary of named key/value pairs. The key value is derived \
    from (:P<name>)
    :returns: None is returned if No match is found.
    :rtype: dict
    :rtype: None
    """
    matcher = re.compile(regex, re.UNICODE)
    match = matcher.match(string)
    if match:
        matches = dict()
        for key in match.groupdict():
            matches[key] = match.group(key)
        return matches
    # No Matches
    return None

Looking at Regex in Rust (Addendum)

Hi. In my previous article Looking at Regex in Rust. I covered some basics. Today I will go over some new things that I have learned, as I expanded on things that my regex expression needs to handle. In particular the need to handle the possible existence or none existence of qualifiers +,-,~,?.

[Read More]

Looking at Regex in Rust

If you have been following this series, you might know that I am playing with SPF records. I have turned my eye to a and mx mechanisms. As I started looking at the a mechanism. I noticed that my current approach using the standard string functions would probably be fairly difficult to implement. So I started to think about using the Regex crate. So this will be a look at how that went. The challenges and the things that I took away from the experience.

[Read More]

Generic Regex Match Function Multiple Groups

If you have read my previous posts; you might know I am currently working on a new project to move some services to a self-hosted solution. As part of this, I have been working on dealing with unicode characters in regex.

In relation to this I have found that I am writing the same function repeatedly. The only difference being the number matches being returned. So I decided we need to refactor this.

[Read More]