import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.util.List;
class Program {
String subject
= "Jane\" \"Tarzan12\" Tarzan11@Tarzan22 {4 Tarzan34}"; Pattern regex = Pattern.compile("\\{[^}]+\\}|\"Tarzan\\d+\"|(Tarzan\\d+)");
Matcher regexMatcher = regex.matcher(subject);
List<String> group1Caps = new ArrayList<String>();
// put Group 1 captures in a list
while (regexMatcher.find()) {
if(regexMatcher.group(1) != null) {
group1Caps.add(regexMatcher.group(1));
}
} // end of building the list
///////// The six main tasks we're likely to have ////////
// Task 1: Is there a match?
System.
out.
println("*** Is there a Match? ***"); if(group1Caps.
size()>0) System.
out.
println("Yes"); else System.
out.
println("No");
// Task 2: How many matches are there?
System.
out.
println("\n" + "*** Number of Matches ***"); System.
out.
println(group1Caps.
size());
// Task 3: What is the first match?
System.
out.
println("\n" + "*** First Match ***"); if(group1Caps.
size()>0) System.
out.
println(group1Caps.
get(0));
// Task 4: What are all the matches?
System.
out.
println("\n" + "*** Matches ***"); if(group1Caps.size()>0) {
}
// Task 5: Replace the matches
// if only replacing, delete the line with the first matcher
// also delete the section that creates the list of captures
Matcher m = regex.matcher(subject);
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, "Superman");
else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced
= b.
toString(); System.
out.
println("\n" + "*** Replacements ***");
// Task 6: Replace the matches
// Start by replacing by something distinctive,
// as in Step 5. Then split.
String[] splits
= replaced.
split("Superman"); System.
out.
println("\n" + "*** Splits ***");
} // end main
} // end Program