fork download
  1. import re
  2.  
  3. string = """
  4. abc@1.0 name='abc'
  5. abc@1.0 dep= {
  6. "this",
  7. "that",
  8. }
  9. abc@2.0 someInfo = "blahblah"
  10. abc@2.0 name='abc'
  11. abc@2.0 dep= {
  12. "this",
  13. "that",
  14. }
  15. abc@2.0 someInfo = "blahblah"
  16. abc@2.0 name='abc'
  17. abc@2.0 dep= {
  18. "this",
  19. "that",
  20. }
  21. abc@2.0 someInfo = "blahblah"
  22. """
  23.  
  24. def getResults(needle=None):
  25. """ Analyze the outer structure """
  26. # outer regex
  27. rx = re.compile(re.escape(needle) + r''' # escape the needle to look for
  28. \s*
  29. (?P<key>\w+) # the key
  30. \s*=\s*
  31. (?:
  32. (['"])(?P<value>.+?(?!\\))\2 # a single value
  33. |
  34. \{(?P<values>[^{}]+)\} # multiple values in {}
  35. )''', re.VERBOSE)
  36.  
  37. def parseInnerValues(values=None):
  38. """ Parse the inner values """
  39. # inner regex
  40. rxi = re.compile(r'''(["'])(.+?)(?<!\\)\1''')
  41. return [m.group(2) for m in rxi.finditer(values)]
  42.  
  43. def getValues(match=None):
  44. """ Decide """
  45. if match.group('values'):
  46. return parseInnerValues(match.group('values'))
  47. else:
  48. return match.group('value')
  49.  
  50. matches = {match.group('key') : getValues(match)
  51. for match in rx.finditer(string)
  52. }
  53. return matches
  54.  
  55. print(getResults('abc@2.0'))
Success #stdin #stdout 0.02s 28384KB
stdin
Standard input is empty
stdout
{'name': 'abc', 'someInfo': 'blahblah', 'dep': ['this', 'that']}