1

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!

mika
  • 86
  • 8

1 Answers1

3

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()
trincot
  • 317,000
  • 35
  • 244
  • 286
  • This works flawlessly. Maybe a little bit of explanation for the OP: the difference of the regex is the "+" sign between the brakets: it means that more than one capital letter can be matched (eg: "Key" and "KEY"). Then the "capitalize()" function converts the first letter to uppercase and the rest to lowercase ("KEY" to "Key") – Daniel Cruz Oct 22 '22 at 23:26