Java String Handling RegEx

Check if String starts with another String in Java example

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

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

You can use startsWith method of String class to check if String starts with another string.

startsWIth method returns true if the string starts with the argument string, false otherwise.

Output

Note:

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

Output

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

1) Using OR operator

Suppose you want to check if the string starts with any of the given multiple string values. Since startsWith 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 starts with any of the given multiple values as given below.

Output

We have used “^(Sat|Sun).*$” pattern to check if the day starts with “Sat” or “Sun”, where

3) Using Apache Commons library

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

Output

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

By default, startsWith 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 startsWithIgnoreCase 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: