Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

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

Learn to use the String.startsWith() and StringUtils class for checking a String prefix against a single value or multiple values.

Lokesh Gupta

October 11, 2023

Java String class
Java String
Java String

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
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

String Examples

  • String Constant Pool
  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • Align Left, Right, Center
  • Immutable Strings
  • StringJoiner
  • Split a string
  • Escape HTML
  • Unescape HTML
  • Convert to title case
  • Find duplicate words
  • Left pad a string
  • Right pad a string
  • Reverse recursively
  • Leading whitespaces
  • Remove whitespaces
  • Reverse words
  • Find duplicate characters
  • Get first 4 characters
  • Get last 4 characters
  • (123) 456-6789 Pattern
  • Interview Questions

String Methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

Table of Contents

  • 1. String Starts with Specified Prefix or Value
  • 2. String Starts with Specified Prefix “Ignoring Case”
  • 3. Check if a String Starts with One of Multiple Values
    • 3.1. Using StringUtils
    • 3.2. Using Regex
    • 3.3. Using For-Loop
  • 4. Conclusion
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Spring Boot Remoting – Spring RMI annotation example

Next

Java String endsWith()

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.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap