On this Page

Regex matching at end of string - dollar($) anchor

The dollar($) is used to match pattern expectations at the end of a string.

For instance the regex ant$ expects the last characters in our string to be ‘ant’.

Example  -Lets apply the above regex(ant$) to below inputs and see the outputs

Input string

Matched found?

Explanation

elephant

YES

Word ends with ant

cant

YES

Word ends with ant

gallant

YES

Word ends with ant

great

NO

Word does not end with ant

dent

NO

Word does not end with ant

boy

NO

Word does not end with ant

1abcc

NO

Word does not end with ant

 

Sample program that does above matches

package devsought;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

public class Regex7 {

 

    public static void main(String... args) {

        String str = "1abcc";

        Pattern pattern = Pattern.compile("ant$");

        Matcher matcher = pattern.matcher(str);

        boolean matchFound = false;

        while (matcher.find()) {

            System.out.println("YES::" + matcher.group());

            matchFound = true;

        }

        if (!matchFound) {

            System.out.println("NO");

        }

    }

}

The abouve code outputs NO . 

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.