fork(10) download
  1. import java.util.*;
  2. import java.io.*;
  3. import java.util.regex.*;
  4. import java.util.List;
  5.  
  6. class Program {
  7. public static void main (String[] args) throws java.lang.Exception {
  8.  
  9. String subject = "Jane\" \"Tarzan12\" Tarzan11@Tarzan22 {4 Tarzan34}";
  10. Pattern regex = Pattern.compile("\\{[^}]+\\}|\"Tarzan\\d+\"|(Tarzan\\d+)");
  11. Matcher regexMatcher = regex.matcher(subject);
  12. List<String> group1Caps = new ArrayList<String>();
  13.  
  14. // put Group 1 captures in a list
  15. while (regexMatcher.find()) {
  16. if(regexMatcher.group(1) != null) {
  17. group1Caps.add(regexMatcher.group(1));
  18. }
  19. } // end of building the list
  20.  
  21. ///////// The six main tasks we're likely to have ////////
  22.  
  23. // Task 1: Is there a match?
  24. System.out.println("*** Is there a Match? ***");
  25. if(group1Caps.size()>0) System.out.println("Yes");
  26. else System.out.println("No");
  27.  
  28. // Task 2: How many matches are there?
  29. System.out.println("\n" + "*** Number of Matches ***");
  30. System.out.println(group1Caps.size());
  31.  
  32. // Task 3: What is the first match?
  33. System.out.println("\n" + "*** First Match ***");
  34. if(group1Caps.size()>0) System.out.println(group1Caps.get(0));
  35.  
  36. // Task 4: What are all the matches?
  37. System.out.println("\n" + "*** Matches ***");
  38. if(group1Caps.size()>0) {
  39. for (String match : group1Caps) System.out.println(match);
  40. }
  41.  
  42. // Task 5: Replace the matches
  43. // if only replacing, delete the line with the first matcher
  44. // also delete the section that creates the list of captures
  45. Matcher m = regex.matcher(subject);
  46. while (m.find()) {
  47. if(m.group(1) != null) m.appendReplacement(b, "Superman");
  48. else m.appendReplacement(b, m.group(0));
  49. }
  50. m.appendTail(b);
  51. String replaced = b.toString();
  52. System.out.println("\n" + "*** Replacements ***");
  53. System.out.println(replaced);
  54.  
  55. // Task 6: Replace the matches
  56. // Start by replacing by something distinctive,
  57. // as in Step 5. Then split.
  58. String[] splits = replaced.split("Superman");
  59. System.out.println("\n" + "*** Splits ***");
  60. for (String split : splits) System.out.println(split);
  61.  
  62. } // end main
  63. } // end Program
Success #stdin #stdout 0.07s 381184KB
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}