If you are not looking for a general solution to convert any regex into a formatting string, but something that you can hardcode:
twitter_url = 'twitter.com/%(username)s/' % {'username': 'dir01'}
...should give you what you need.
If you want a more general (but not incredibly robust solution):
import re
def format_to_re(format):
# Replace Python string formatting syntax with named group re syntax.
return re.compile(re.sub(r'%\((\w+)\)s', r'(?P<\1>\w+)', format))
twitter_format = 'twitter.com/%(username)s/'
twitter_re = format_to_re(twitter_format)
m = twitter_re.search('twitter.com/dir01/')
print m.groupdict()
print twitter_format % m.groupdict()
Gives me:
{'username': 'dir01'}
twitter.com/dir01/
And finally, the slightly larger and more complete solution that I have been using myself can be found in the Pattern
class here.