Java Regex Anchors Example

Anchors match the positions of characters inside a given text. In the next example, we look if a string is located at the beginning of a sentence.

Java Regex Anchors Example

In the below example, we have three sentences. The search pattern is ^Prabhas. The pattern checks if the "Prabhas" string is located at the beginning of the text. Prabhas.$ would look for "Prabhas" at the end of the sentence.
package net.javaguides.corejava.regex;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaRegexAnchorExample {

    public static void main(String[] args) {

        List < String > sentences = Arrays.asList("I am looking for Prabhas",
            "Prabhas is an Actor",
            "Mahesh and Prabhas are close friends");

        Pattern p = Pattern.compile("^Prabhas");

        for (String word: sentences) {

            Matcher m = p.matcher(word);

            if (m.find()) {
                System.out.printf("%s -> matches%n", word);
            } else {
                System.out.printf("%s -> does not match%n", word);
I am looking for Prabhas -> does not match
Prabhas is an Actor -> matches
Mahesh and Prabhas are close friends -> does not match