THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Matcher matcher = pat.matcher(input);
return matcher.replaceAll("$3$2$1");
}


First we build a pattern from the two words, using parenthesis to capture 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 characters), 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");
}


13.3.4. Regions


A Matcher looks for matches in the character sequence that it is given as input. By default, the entire
character sequence is considered when looking for a match. You can control the region of the character
sequence to be used, through the method region which takes a starting index and an ending index to define
the subsequence in the input character sequence. The methods regionStart and regionEnd return,
respectively, the current start index and the current end index.


You can control whether a region is considered to be the true start and end of the input, so that matching with
the beginning or end of a line will work, by invoking useAnchoringBounds with an argument of true
(the default). If you don't want the region to match with the line anchors then use false. The method
hasAnchoringBounds will return the current setting.


Similarly, you can control whether the bounds of the region are transparent to matching methods that want to
look-ahead, look-behind, or detect a boundary. By default bounds are opaquethat is, they will appear to be
hard bounds on the input sequencebut you can change that with useTransparentBounds. The
hasTransparentBounds method returns the current setting.

Free download pdf