The following table lists all boundary matchers that can be used in a regular expression.
Boundary Matchers | Meaning |
---|---|
^ | 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:
A non-word boundary matches the following:
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.
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 }