Check if String Starts With a Prefix or Multiple Values in Java

When working with strings in Java, many times we need to check the prefixes of a String in tasks like input validation, filtering, and data processing. This Java article explores different techniques to check if a string starts with a specified value or one among the multiple values in Java.

1. String Starts with Specified Prefix or Value

Java String.startsWith() method checks if a string begins with the specified prefix substring. The argument prefix must be a standard substring and the regular expressions are not supported.

The startsWith() method is an overloaded method and has two forms:

  • boolean startsWith(substring) – returns true if the substring is a prefix of the String.
  • boolean startsWith(substring, fromIndex) – returns true if the String begins with substring starting from the specified index fromIndex.

The following Java program checks if a string starts with the specified prefixes.

String blogName = "howtodoinjava.com";

boolean result = blogName.startsWith("how");   // true
boolean result = blogName.startsWith("howto");   // true
boolean result = blogName.startsWith("hello");   // false

boolean result = blogName.startsWith("do", 0);   // false
boolean result = blogName.startsWith("do", 5);   // true

Note that the startsWith() does not support regular expressions as an argument. If we pass the regex as an argument, it will only be treated as a normal string.

String blogName = "howtodoinjava.com";

Assertions.assertFalse(blogName.startsWith("^h")); 

If you want to check the prefix with regular expressions, then you can use the Pattern and Matcher API.

2. String Starts with Specified Prefix “Ignoring Case”

If we want to check the String prefix in a case-insensitive manner, we can use the Apache Common Lang’s StringUtils class. Its startsWithIgnoreCase() method performs a case-insensitive check if a String starts with a specified prefix.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Let us see a quick example.

String text = "The quick brown fox jumps over the lazy dog";

boolean result = StringUtils.startsWithIgnoreCase(text, "the");

System.out.println(result);   // true

3. Check if a String Starts with One of Multiple Values

If we have multiple prefixes to check, and String can begin with any one of the prefixes then we can use one of the following approaches.

3.1. Using StringUtils

Apache Common Lang’s StringUtils class is the most clean approach that can help in determing if a String starts with any one prefix from the multiple values. Its startsWithAny() method checks if a String starts with any of the provided case-sensitive prefixes passed as varargs.

Lets see a quick example to understand the usage of startsWithAny() method.

String text = "The quick brown fox jumps over the lazy dog";

boolean result = StringUtils.startsWithAny(text, "The", "A", "An");

System.out.println(result);   // true

3.2. Using Regex

Another way to check if a string starts with specific values is to use regular expressions. Regular expressions allow for more complex pattern matching, making them useful when you have multiple values to check.

String text = "The quick brown fox jumps over the lazy dog";
String[] prefixes = { "The", "A", "An" };

String regex = "^(?:" + String.join("|", prefixes) + ").*";    // ^(?:The|A|An).*

if (Pattern.compile(regex).matcher(text).matches()) {
  System.out.println("The string starts with one of the specified values.");
} else {
  System.out.println("The string does not start with any of the specified values.");
}

3.3. Using For-Loop

If none seems good enough, you can use a for-loop to iterate through an array or a collection of prefixes and check each one using the startsWith() method.

String text = "The quick brown fox jumps over the lazy dog";
String[] prefixes = { "The", "A", "An" };

for (String prefix : prefixes) {
  if (text.startsWith(prefix)) {
    System.out.println("The string starts with '" + prefix + "'.");
    break; // Exit the loop when a match is found
  }
}

4. Conclusion

This Java tutorial explored the use of startsWith() and other methods for checking a String prefix against a single value or multiple values.

As seen above, Apache Common Lang’s StringUtils is the cleanest and recommended approach in case of checking against multiple values.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.