More Pythonic, removed redundant code, added named group capture, using regexes for escaping