Java String Handling RegEx

Check if String ends with another String in Java example

This Java example shows how to check if String ends with another String using endsWith method. Example also shows how to check if String ends with another string using regular expression or case insensitive comparison.

How to check if String ends with another String in Java?

You can use endsWith method of String class to check if String ends with another string.

endsWIth method returns true if the string ends with the argument string, false otherwise.

Output

Note:

endsWith always returns true for empty string or if the string is equal to the argument string. For example,

Output

How to check if String ends with any of the given Strings?

1) Using OR operator

Suppose you want to check if the string ends with any of the given multiple string values. Since endsWith method accepts only one argument, you need to check it multiple times using OR (||) operator as given below.

Output

2) Using Regular Expression

You can also use regular expression to check if the String ends with any of the given multiple values as given below.

Output

We have used "^.*(\\.txt|\\.rtf)$" pattern to check if the file name ends with “.txt” or “.rtf”, where

Dot (.) has a special meaning in the regular expression (it matches any character). Hence, in order to do literal search of dot in a string, we need to escape it like “\\.”.

3) Using Apache Commons library

If you are using Apache Commons library, you can use endsWithAny method of StringUtils class to check if the String ends with any of the given multiple Strings as given below.

Output

How to check if String ends with other String using case insensitive comparison?

By default, endsWith is case sensitive. For example,

will return “false”.

You can use toLowerCase (or toUpperCase) method to change the case of the both the strings as given below.

Output

If you are using Apache Commons library, you can use endsWithIgnoreCase method of StringUtils class to do case insensitive comparison as given below.

Output

Please let us know your views in the comments section below.

 

Join 1000+ fellow learners! Enter your email address below: