Skip to content

Instantly share code, notes, and snippets.

@emedvedev
Last active September 11, 2015 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emedvedev/334af6223626bddf3207 to your computer and use it in GitHub Desktop.
Save emedvedev/334af6223626bddf3207 to your computer and use it in GitHub Desktop.
import re
def parse(template, string):
result = {}
# getting a full list of params with their default values if present
params_list = re.findall(r'{{\s*(.+?)\s*(?:=(.+?))?\s*}}', template)
# compiling a regexp: it's almost fully copied from hubot-stackstorm,
# but note the named grouping
reg = re.sub(r'\s+{{\s*(\w+)\s*=.+?\s*}}', r'(?:\s+(?P<\1>.+?))?', template)
reg = re.sub(r'{{\s*(.+?)\s*}}', r'(?P<\1>.+?)', reg)
reg = reg + r'(\s+)?(\s?(\w+)=(\w+)){0,}$'
print reg
match = re.match(reg, string)
if match:
values_dict = match.groupdict()
# iterating through a list of params and substituting with default
# values if something's not present
for param in params_list:
result[param[0]] = values_dict[param[0]] or param[1]
return result
print parse("chatopsaction {{ string }}", "chatopsaction word1")
# {'string': 'word1'}
print parse("chatopsaction {{ string }}", "chatopsaction word1 word2")
# {'string': 'word1 word2'}
print parse("chatopsaction {{ string }} {{ string2=default }}", "chatopsaction word1 word2")
# {'string2': 'word2', 'string': 'word1'}
print parse("chatopsaction {{ string }} {{ string2=default }}", "chatopsaction word1")
# {'string2': 'default', 'string': 'word1'}
print parse("chatopsaction {{ string }} {{ string2=default }} {{ string3=default }}", "chatopsaction word1")
# {'string2': 'default', 'string': 'word1', 'string3': 'default'}
print parse("chatopsaction {{ string }} {{ string2 }} {{ string3=default }}", "chatopsaction word1 word2 word3")
# {'string2': 'word2', 'string': 'word1', 'string3': 'word3'}
print parse("chatopsaction {{ string }} {{ string2 }}", "chatopsaction word1 word2 word3")
# {'string2': 'word2 word3', 'string': 'word1'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment