Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active October 3, 2016 21:37
Show Gist options
  • Save cb109/b440e8786f018b8f100469ee0ac4c72d to your computer and use it in GitHub Desktop.
Save cb109/b440e8786f018b8f100469ee0ac4c72d to your computer and use it in GitHub Desktop.
Resolve tokens in strings
# :coding: utf-8
"""Replace tokens in strings."""
import re
DOUBLE_CURLY_BRACED_TOKEN = r"{{\s*(\w+)\s*}}" # E.g.: '{{ token }}'
def resolve(tokenstr, replacements, pattern=DOUBLE_CURLY_BRACED_TOKEN):
"""Apply the replacements dict to the string that contains tokens.
The replacements can contain tokens themselves: All tokens will be
expanded if a replacement exists.
"""
def replace(match):
"""Return replacement for token of match object."""
token_name = match.groups()[0]
return replacements[token_name]
tokenstr, count_replaced = re.subn(pattern, replace, tokenstr)
# If we replaced at least one thing, we may have added new tokens
# with that replacement, so give it another try. When the count
# reaches 0, we have expanded all tokens that we know of.
while count_replaced:
tokenstr, count_replaced = re.subn(pattern, replace, tokenstr)
return tokenstr
def test_resolve():
teststring = "This is a {{ nested }} {{ test }}, {{mod}}."
replacements = {"test": "working example",
"nested": "{{ mod }}",
"mod": "really"}
expectation = "This is a really working example, really."
result = resolve(teststring, replacements)
assert result == expectation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment