fork download
  1. import re
  2. subject = 'a1,a2,a3,a4,{_some_length_not_known_in_advance,a6}'
  3. regex = re.compile(r'{[^}]*}|(,)')
  4. # put Group 1 captures in a list
  5. matches = [group for group in re.findall(regex, subject) if group]
  6.  
  7. # How many matches are there?
  8. print("\n" + "*** Number of Matches ***")
  9. print(len(matches))
  10.  
  11. # What are all the matches?
  12. print("\n" + "*** Matches ***")
  13. if len(matches)>0:
  14. for match in matches:
  15. print (match)
  16.  
  17. # Replace the matches
  18. def myreplacement(m):
  19. if m.group(1):
  20. return "SplitHere"
  21. else:
  22. return m.group(0)
  23. replaced = regex.sub(myreplacement, subject)
  24. print("\n" + "*** Replacements ***")
  25. print(replaced)
  26.  
  27. # Split
  28. # Start by replacing by something distinctive as above,
  29. # then split.
  30. splits = replaced.split('SplitHere')
  31. print("\n" + "*** Splits ***")
  32. for split in splits:
  33. print (split)
Success #stdin #stdout 0.03s 9440KB
stdin
Standard input is empty
stdout
*** Number of Matches ***
4

*** Matches ***
,
,
,
,

*** Replacements ***
a1SplitHerea2SplitHerea3SplitHerea4SplitHere{_some_length_not_known_in_advance,a6}

*** Splits ***
a1
a2
a3
a4
{_some_length_not_known_in_advance,a6}