This is similar to @moliware's solution, but there's no hard-coding of keys required in this solution:
import re
class mydict(dict):
def __missing__(self, key):
self.setdefault(key, '')
return ''
def solve(a, b):
dic = mydict()
a % dic
strs = a
for x in dic:
esc = re.escape(x)
strs = re.sub(r'(%\({}\).)'.format(esc), '(?P<{}>.*)'.format(esc), strs)
return re.search(strs, b).groupdict()
if __name__ == '__main__':
a = '/stock/%(symbol)s/%(property)s'
b = '/stock/AAPL/price'
print solve(a, b)
a = "Foo %(bar)s spam %(eggs)s %(python)s"
b = 'Foo BAR spam 10 3.x'
print solve(a, b)
Output:
{'symbol': 'AAPL', 'property': 'price'}
{'python': '3.x', 'eggs': '10', 'bar': 'BAR'}
As @torek pointed out for cases with ambiguous output(no space between keys) the answer can be wrong here.
For eg.
a = 'leading/%(A)s%(B)s/trailing'
b = 'leading/helloworld/trailing'
Here looking at just b
it's hard to tell the actual value of either either A
or B
.