You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.3 KiB

7 years ago
  1. import re
  2. paren = re.compile(r"\([^\(\)]*\)")
  3. def whiteout(s,start,end):
  4. return s[:start] + (' '*(end-start)) + s[end:]
  5. def endparen(s,start):
  6. end = None
  7. while end == None:
  8. span = paren.search(s,start).span()
  9. if span[0] == start:
  10. end = span[1]
  11. else:
  12. s = whiteout(s,*span)
  13. return end
  14. def find_named_groups(regex):
  15. start = 0
  16. while start < len(regex)-1:
  17. try:
  18. start = regex.index('(?P',start)
  19. yield start
  20. start += 1
  21. except ValueError:
  22. break
  23. def named_group_split(regex):
  24. named_groups = list(find_named_groups(regex))
  25. for index in range(len(named_groups)):
  26. s0 = named_groups[index]
  27. e0 = endparen(regex,s0)
  28. s1 = e0
  29. try:
  30. if not e0 == named_groups[index+1]:
  31. e1 = named_groups[index+1]
  32. else:
  33. e1 = s1
  34. except IndexError:
  35. s1 = e0
  36. e1 = len(regex)+1
  37. yield [regex[s0:e0],regex[s1:e1]]
  38. def wrap(s):
  39. if s:
  40. return 'r"{}"'.format(s)
  41. else:
  42. return ''
  43. def sep_row(row,lengths,add_sep = 0):
  44. ret = ''
  45. for col in range(len(row)-1):
  46. if row[col+1]:
  47. ret += row[col].ljust(lengths[col]+add_sep,' ')
  48. else:
  49. ret += row[col]
  50. return ret + row[-1]
  51. def list2dstring(list2d,space=1):
  52. col_length = []
  53. for col in range(len(list2d[0])-1):
  54. col_length.append(
  55. max(
  56. map(
  57. len,(row[col] for row in list2d)
  58. )
  59. )
  60. )
  61. col_length.append(0)
  62. ret = []
  63. for row in list2d:
  64. ret.append(sep_row(list(map(wrap,row)),col_length,add_sep = 4))
  65. return '\n'.join(ret)
  66. def pformat_regex(regex):
  67. return '\n'+list2dstring(list(named_group_split(regex)))+'\n'
  68. if __name__ == "__main__":
  69. from Npp import editor
  70. start = editor.getSelectionStart()
  71. content = editor.getSelText()
  72. prev_content = content
  73. content = re.sub(r'^\(?r?[\"\']|[\"\']\)?','',content)
  74. result = pformat_regex(content)
  75. if prev_content[0] == '(':
  76. result = '(' + result
  77. if prev_content[-1] == ')':
  78. result = result + ')'
  79. editor.replaceSel(result)
  80. editor.setSelectionStart(start)
  81. editor.setSelectionEnd(start + len(result))