Search code examples
regexdjango-template-filterspython-regex

python - Wrong regex used?


Here is my func:

@register.filter
def load_human_key(key):
    """
    load util based on typ for key
    return: More readable key
    """
    
    regex = re.findall('[A-Z][^A-Z]*', key)

    if regex:
        joined_regex = " ".join(regex)
        return joined_regex
    return key

When I use load_human_key("JsonKey"). It works fine and returns Json Key, but when I use load_human_key("JsonKEY") it returns "Json K E Y"), which is not the behaviour i'd like to implement. Can sb help my function, so that load_human_key("JsonKEY") = load_human_key("JsonKey")? I am completly new to regex.

Thanks!


Solution

  • A regex only cannot change characters from upper case to lower case, so you'll need to map each match to take care of that with Python code.

    Not your question, but the naming used in your code is confusing: regex is not the regex, but the list of matches you get from executing one.

    Here is how you could do it:

    def load_human_key(key):
        return re.sub('[A-Z]+[^A-Z]*', lambda m: ' ' + m[0].capitalize(), key).lstrip()