fork(3) download
  1. import re
  2. # import regex # if you like good times
  3. # intended to replace `re`, the regex module has many advanced
  4. # features for regex lovers. http://p...content-available-to-author-only...n.org/pypi/regex
  5. subject = 'Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34}'
  6. regex = re.compile(r'{[^}]+}|"Tarzan\d+"|(Tarzan\d+)')
  7. # put Group 1 captures in a list
  8. matches = [group for group in re.findall(regex, subject) if group]
  9.  
  10. ######## The four main tasks we're likely to have ########
  11.  
  12. # Task 1: Is there a match?
  13. print("*** Is there a Match? ***")
  14. if len(matches)>0:
  15. print ("Yes")
  16. else:
  17. print ("No")
  18.  
  19. # Task 2: How many matches are there?
  20. print("\n" + "*** Number of Matches ***")
  21. print(len(matches))
  22.  
  23. # Task 3: What is the first match?
  24. print("\n" + "*** First Match ***")
  25. if len(matches)>0:
  26. print (matches[0])
  27.  
  28. # Task 4: What are all the matches?
  29. print("\n" + "*** Matches ***")
  30. if len(matches)>0:
  31. for match in matches:
  32. print (match)
  33.  
  34. # Task 5: Replace the matches
  35. def myreplacement(m):
  36. if m.group(1):
  37. return "Superman"
  38. else:
  39. return m.group(0)
  40. replaced = regex.sub(myreplacement, subject)
  41. print("\n" + "*** Replacements ***")
  42. print(replaced)
  43.  
  44. # Task 6: Split
  45. # Start by replacing by something distinctive,
  46. # as in Step 5. Then split.
  47. splits = replaced.split('Superman')
  48. print("\n" + "*** Splits ***")
  49. for split in splits:
  50. print (split)
Success #stdin #stdout 0.01s 7896KB
stdin
Standard input is empty
stdout
*** Is there a Match? ***
Yes

*** Number of Matches ***
2

*** First Match ***
Tarzan11

*** Matches ***
Tarzan11
Tarzan22

*** Replacements ***
Jane"" ""Tarzan12"" Superman@Superman {4 Tarzan34}

*** Splits ***
Jane"" ""Tarzan12"" 
@
 {4 Tarzan34}