Matching Boundaries
So far you have been trying to find the occurrence of a pattern anywhere in a string. In many situations you will want to be more specific. You may want to look for a pattern that appears at the beginning of a line in a string but not anywhere else, or maybe just at the end of any line. For example :
As you saw in the example, you may want to look for a word that is not embedded — you want to find the word “temp” but not the “temp” in “attemporaryt” or in “temporaryting”, for example. This example worked for the string you were searching but would not produce the right result if the word you were looking for was followed by a comma or appeared at the end of the text. However, you have other options for specifying the pattern. You can use a number of special sequences in a regular expression when you want to match a particular boundary. Following some that are particularly useful:
Program
Program Source
import java.util.regex.Pattern; import java.util.regex.Matcher; public class Javaapp { public static void main(String[] args) { Pattern pat = Pattern.compile("\\BJava"); Matcher mat = pat.matcher("Java XXXJavaxx XXJava Java"); int i = 0; while(mat.find()) { i++; System.out.println(i+"th subsequence : "+mat.group()+" : "+mat.start()); } } }