How to Use appendReplacement with Subgroup Replacements

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - How to Use appendReplacement with Subgroup Replacements

This Java example program demonstrates usage of the Matcher.appendReplacement method, with subgroup replacement.

[edit] Java Source Code

  • Package: example.matcher
  • File: MatcherAppendReplacementGroupExample.java
package example.matcher;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class MatcherAppendReplacementGroupExample {
    public static void main(String args[]) {
	Pattern p = Pattern.compile("(James) (Bond)");
	StringBuffer sb = new StringBuffer();
 
	String candidateString = "My name is Bond. James Bond.";
 
	String replacement = "$1 Waldo $2";
 
	Matcher matcher = p.matcher(candidateString);
	matcher.find();
 
	matcher.appendReplacement(sb, replacement);
 
	String msg = sb.toString();
	System.out.println(msg);
    }
 
}

[edit] What Result You Can Get

Run the program, you will get:

My name is Bond. James Waldo Bond

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools