"""
Find and Replace with Regex
Requires Python 3.6+
"""
import re
TEST_STRING = "Hello <name>! Welcome to <place_name>. The date is <date2today>." \
"<place_name> is a great place."
def find_replace(string, pattern=r"<(\w+)>", **values):
matched_result = re.finditer(pattern, string)
for match in matched_result:
value = values.get(match)
if value is not None:
string = re.sub(f"<{match}>", f"<{value}>", string)
return string
if __name__ == '__main__':
new_string = find_replace(TEST_STRING, name="World", place_name="Nigeria",
date2today="February 14, 2019")
print(new_string)
# 'Hello <World>! Welcome to <Nigeria>. The date is <February 14, 2019>. <Nigeria> is a great place.'