fork(1) download
  1. #!/usr/bin/perl
  2. $regex = '{[^}]+}|"Tarzan\d+"|(Tarzan\d+)';
  3. $subject = 'Jane" "Tarzan12" [email protected] {4 Tarzan34}';
  4. # put Group 1 captures in an array
  5. my @group1Caps = ();
  6. while ($subject =~ m/$regex/g) {
  7. print $1 . "\n";
  8. if (defined $1) {push(@group1Caps,$1); }
  9. }
  10.  
  11. ######## The six main tasks we're likely to have ########
  12.  
  13. # Task 1: Is there a match?
  14. print "*** Is there a Match? ***\n";
  15. if ( @group1Caps > 0) { print "Yes\n"; }
  16. else { print ("No\n"); }
  17.  
  18. # Task 2: How many matches are there?
  19. print "\n*** Number of Matches ***\n";
  20. print scalar(@group1Caps);
  21.  
  22. # Task 3: What is the first match?
  23. print "\n\n*** First Match ***\n";
  24. if ( @group1Caps > 0) { print $group1Caps[0]; }
  25.  
  26. # Task 4: What are all the matches?
  27. print "\n\n*** Matches ***\n";
  28. if ( @group1Caps > 0) {
  29. foreach(@group1Caps) { print "$_\n"; }
  30. }
  31.  
  32. # Task 5: Replace the matches
  33. ($replaced = $subject) =~ s/$regex/
  34. if (defined $1) { "Superman"; } else {$&;} /eg;
  35. print "\n*** Replacements ***\n";
  36. print $replaced . "\n";
  37.  
  38. # Task 6: Split
  39. # Start by replacing by something distinctive,
  40. # as in Step 5. Then split.
  41. @splits = split(/Superman/, $replaced);
  42. print "\n*** Splits ***\n";
  43. foreach(@splits) { print "$_\n"; }
  44.  
Success #stdin #stdout 0s 3564KB
stdin
Standard input is empty
stdout
Tarzan11
Tarzan22

*** Is there a Match? ***
Yes

*** Number of Matches ***
2

*** First Match ***
Tarzan11

*** Matches ***
Tarzan11
Tarzan22

*** Replacements ***
Jane" "Tarzan12" [email protected] {4 Tarzan34}

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