Let's look at a complete program to the understand use of these methods.
Consider the following input:
<n1=v1 n2=v2 n3=v3> n1=v1 n2=v2 abc=123 <v=pq id=abc> v=pq
We need to write code to swap each name-value pair enclosed in angular brackets, < and >, while leaving the name-value pairs outside the angular brackets unchanged. After running our code, it should produce the following output:
<v1=n1 v2=n2 v3=n3> n1=v1 n2=v2 abc=123 <pq=v abc=id> v=pq
To solve this problem, we have to first find each match enclosed in angular brackets using the find method in a loop. Inside the loop, we will have to replace each name-value pair using the appendReplacement method. Finally, outside the loop, we will use the appendTail method to append the remaining characters after our last match.
Here is the full code:
package example.regex;
import java.util.regex.*;
class MatcherAppendExample
{
public static void main (String[] args)
{
final String input = "<n1=v1 n2=v2 n3=v3> n1=v1 n2=v2 abc=
123 <v=pq id=abc> v=pq";
// pattern1 to find all matches between < and >
final Pattern pattern = Pattern.compile("<[^>]+>");
// pattern1 to find each name=value pair
final Pattern pairPattern = Pattern.compile("(\w+)=(\w+)");
Matcher enclosedPairs = pattern.matcher(input);
StringBuilder sbuf = new StringBuilder();
// call find in a loop and call appendReplacement for each match
while (enclosedPairs.find())
{
Matcher pairMatcher = pairPattern.matcher(enclosedPairs.group());
// replace name=value with value=name in each match
enclosedPairs.appendReplacement(sbuf,
pairMatcher.replaceAll("$2=$1"));
}
// appendTail to append remaining character to buffer
enclosedPairs.appendTail(sbuf);
System.out.println(sbuf);
}
}
Upon compiling and running, the preceding code will produce the following output:
<v1=n1 v2=n2 v3=n3> n1=v1 n2=v2 abc=123 <pq=v abc=id> v=pq
As you can see, the final output has all the name=value pairs swapped inside the angular brackets.