Java Reference
In-Depth Information
First we build a pattern from the two words, using parenthesis to cap-
ture groups of characters. A \b in a pattern matches a word boundary
(otherwise the word "crow" would match part of "crown"), and \W
matches any character that would not be part of a word. The original
pattern matches groups one (the first word), two (the separator char-
acters), and three (the second word), which the "$3$2$1" replacement
string inverts.
For example, the invocation
swapWords("up", "down",
"The yo-yo goes up, down, up, down, ...");
would return the string
The yo-yo goes down, up, down, up, ...
If we only wanted to swap the first time the words were encountered we
could use replaceFirst :
public static String
swapFirstWords(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.replaceFirst("$3$2$1");
}
 
Search WWH ::




Custom Search