In this short tutorial, we are going to shed light on how to use the regex “ends with” to match the last part of a string.

First, we will start with a few insights into what the anchor $ means. Then, we are going to explain using examples how to match the end of a string.

Anchor Dollar Ends With

Anchors are metacharacters that don’t match any character at all. Instead, they assert something about the string such as a position before or after characters.

The dollar sign ”$” matches the very end of a given string. For instance, .*hello$ expects that the last portion of our string must be hello.

Please note that ”.” is a regex wildcared that represents any character except a line terminator. “*“ is a quantifier that indicates any number of times.

Now that we know what the anchor ”$” means, let’s see how to use it to match the end of a string.

The caret ”^” is another anchor that denotes the beginning of a string. Our article on how to use the starts with regex and does a great job of explaining it.

Matching the End of String

As we mentioned earlier, we can use the dollar anchor in a regex to denote the position after the last character in a given string.

Regex Example Description
word$ matches any string that ends with "word"
\\d$ or [0-9]$ matches a string ending with a number
[a-zA-Z]$ any string ends with a letter in a case-insensitive manner
\s$ any string ending with space

Now, let’s exemplify each regex using practical examples in Java:

    
        public static void main(String[] args) {
        Pattern.compile("us$")
            .matcher("devwithus")
            .find(); // true

        Pattern.compile("[0-9]$")
            .matcher("Position 2")
            .find(); // true
            
        Pattern.compile("\\d$")
            .matcher("Year 2023")
            .find(); // true
            
        Pattern.compile("\s$")
            .matcher("space ")
            .find(); // true

        Pattern.compile("[a-zA-Z]$")
            .matcher("devwithus.CoM")
            .find(); // true
        }
    

Please bear in mind that the dollar anchor, by design, matches the position after the very last character in the whole string.

So, in case we want to match the end of each line, we need to build a custom regex.

Conclusion

In this tutorial, we explained what the anchor $ means. Along the way, we showcased how to use the dollar sign in a regex to match the end of a string.

Lastly, we saw how to find a string that ends with multiple patterns.