fork download
  1. import re
  2.  
  3. regex = r"^([^;]+);[\r\n]*([^;]+);[\r\n]*([^;]+);"
  4.  
  5. test_str = ("New York City; Iron Man; no superpowers;\n"
  6. "Metropolis; Superman; superpowers;\n"
  7. "New York City;\n"
  8. "Spider-Man;\n"
  9. "superpowers;\n"
  10. "Gotham; Batman; no superpowers;\n"
  11. "New York City; Doctor Strange; superpowers;\n\n")
  12.  
  13. subst = "\\1;\\2;\\3;"
  14.  
  15. # You can manually specify the number of replacements by changing the 4th argument
  16. result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.DOTALL)
  17.  
  18. if result:
  19. print (result)
Success #stdin #stdout 0s 23296KB
stdin
Standard input is empty
stdout
New York City; Iron Man; no superpowers;
Metropolis; Superman; superpowers;
New York City;Spider-Man;superpowers;
Gotham; Batman; no superpowers;
New York City; Doctor Strange; superpowers;