This post will check if a check if a String matches one of the given prefixes in Java.

1. Using OR operator

We can use the String.startsWith() method, which returns true if the string starts with the specified prefix, and false otherwise. A naive approach is to use this method to test against all possible prefixes inside a conditional statement using the OR operator.

Download  Run Code

2. Regular expressions

Another way to check if a string matches one of the given prefixes is to use the String.matches() method. This method returns true if the string matches a given regular expression, and false otherwise. We can use the ^ symbol to indicate the start of the string in the regex. We can also use the | symbol to specify multiple prefixes in the regex, such as str.matches("^(AA|AB|BC).*"). Here is a sample code that demonstrates this method:

Download  Run Code

3. Using Java 8 Stream

Alternatively, we can use the anyMatch() method from the Java 8 Streams API. This method allows us to create a stream of prefixes and apply a predicate function to each element to check if the string starts with it. The anyMatch() method returns true if any element of the stream matches the predicate, and false otherwise. For example, we can use the following code to check if a string matches one of the given prefixes:

Download  Run Code

4. Using Apache Commons Lang

Finally, we can use the external libraries such as Apache Commons Lang, which provides the StringUtils.startsWithAny() method. This method takes a string and an array of prefixes as arguments and returns true if the string starts with any of the prefixes, and false otherwise.

Download Code

That’s all about checking if a String matches one of the given prefixes in Java.