Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Regular expressions simplify pattern-matching code

Discover the elegance of regular expressions in text-processing scenarios that involve pattern matching

  • Print
  • Feedback

Page 13 of 16

one caterpillar, two caterpillars, or three caterpillars on a fence


Two other text replacement methods make it possible to replace either the first match or all matches with replacement text:

  • public String replaceFirst(String replacement): resets the matcher, creates a new String object, copies all the matcher's text characters (up to the first match) to String, appends the replacement characters to String, copies remaining characters to String, and returns that object's reference. (The replacement string may contain references to text sequences captured during the previous match, via dollar-sign characters and capturing group numbers.)
  • public String replaceAll(String replacement): operates similarly to the previous method. However, replaceAll(String replacement) replaces all matches with replacement's characters.


The \s+ regex detects one or more occurrences of whitespace characters in text. The following example uses that regex and calls the replaceAll(String replacement) method to remove duplicate whitespace from text:

Pattern p = Pattern.compile ("\\s+");
Matcher m = p.matcher ("Remove     the \t\t duplicate whitespace.   ");
System.out.println (m.replaceAll (" "));


The example produces the following output:

  • Print
  • Feedback

Resources