Java Reference
In-Depth Information
Pattern pat = Pattern.compile("sun");
Matcher matcher = pat.matcher(input);
String result = matcher.replaceAll("moon");
As an example of a more complex usage of regular expressions, here is
code that will replace every number with the next largest number:
Pattern pat = Pattern.compile("[-+]?[0-9]+");
Matcher matcher = pat.matcher(input);
StringBuffer result = new StringBuffer();
boolean found;
while ((found = matcher.find())) {
String numStr = matcher.group();
int num = Integer.parseInt(numStr);
String plusOne = Integer.toString(num + 1);
matcher.appendReplacement(result, plusOne);
}
matcher.appendTail(result);
Here we decode the number found by the match, add one to it, and re-
place the old value with the new one.
The replacement string can contain a $ g , which will be replaced with
the value from the g th capturing group in the expression. The following
method uses this feature to swap all instances of two adjacent words:
public static String
swapWords(String w1, String w2, String input)
{
String regex = "\\b(" + w1 + ")(\\W+)(" + w2 + ")\\b";
Pattern pat = Pattern.compile(regex);
Matcher matcher = pat.matcher(input);
return matcher.replaceAll("$3$2$1");
}
 
Search WWH ::




Custom Search