Monday, October 29, 2007

An example of Regular Expression search and replace program

This Java tip illustrates an example of Quintessential Regular Expression search and replace program. This program finds all matches to a regular expression pattern and replaces them with another string.

import java.util.regex.*;

public class BasicReplace {

public static void main(String[] args) {

CharSequence inputStr = "p q r p q r ";
String patternStr = "q";
String replacementStr = "s";

// Compile regular expression
Pattern pattern = Pattern.compile(patternStr);

// Replace all occurrences of pattern in input
Matcher matcher = pattern.matcher(inputStr);
String output = matcher.replaceAll(replacementStr);
// p s r p s r
}
}

No comments: