import re


def change_merge_field_name_for_text(text, previous_attribute_name, new_attribute_name):
    """
        This function processes text and replaces any instances of merge fields of the previous
        attribute name with the new attribute name.  For example, if we're editing an attribute
        name from "foo" to "bar", this would convert the text "Hello [[foo]]" to "Hello [[bar]]".
    """
    # set up regex
    regex_pattern = r"\[\[[ ]?" + re.escape(previous_attribute_name) + "[ ]?\]\]"  # the space is optional "[[thing]]"
    regex = re.compile(regex_pattern, re.IGNORECASE)  # ignore case
    # do regex and replace with uppered new attribute name
    return regex.sub("[[%s]]" % new_attribute_name.upper(), text)