Last active
September 11, 2015 17:40
-
-
Save emedvedev/334af6223626bddf3207 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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