Java - Regular Expressions Matching Boundaries

Introduction

The following table lists all boundary matchers that can be used in a regular expression.

Boundary MatchersMeaning
^The beginning of a line
$The end of a line
\b A word boundary
\B A non-word boundary
\A The beginning of the input
\G The end of previous match
\Z The end of the input but for the final terminator, if any
\z The end of the input

A word boundary is a zero-width match that can match the following:

  • Between a word character and a non-word character
  • Start of the string and a word character
  • A word character and the end of the string

A non-word boundary matches the following:

  • The empty string
  • Between two word characters
  • Between two non-word characters
  • Between a non-word character and the start or end of the string

To match the word apple, use \bapple\b, which means the following: a word boundary, the word apple, and a word boundary.

The following code demonstrates how to match a word boundary using a regular expression.

Demo

public class Main {
  public static void main(String[] args) {
    // Prepare regular expression. 
    //Use \\b to get \b inside the string literal.
    String regex = "\\bapple\\b";
    String replacementStr = "orange";
    String inputStr = "an apple and five bats";
    String newStr = inputStr.replaceAll(regex, replacementStr);

    System.out.println("Regular Expression: " + regex);
    System.out.println("Input String: " + inputStr);
    System.out.println("Replacement String: " + replacementStr);
    System.out.println("New String: " + newStr);
  }//from  w w w.  jav a2s.co  m
}

Result