Skip to content

Instantly share code, notes, and snippets.

@chumaumenze
Last active August 15, 2019 00:56
Show Gist options
  • Save chumaumenze/e4322cf32afb46bc00b938f9a3c203eb to your computer and use it in GitHub Desktop.
Save chumaumenze/e4322cf32afb46bc00b938f9a3c203eb to your computer and use it in GitHub Desktop.
Find and Replace with Regex
"""
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.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment