In this article, we will see how to find if the given substring is present in the entire string or not.

Java’s java.util.regex package provides classes such as Pattern and Matcher to perform the substring matching.

First, import the required packages as shown below

import java.util.regex.*;

Define the regular expression pattern which represents the substring that we want to find within the larger string.

If we want to find the string "car" in a string, then define the regular expression pattern as "car".

String pattern = "car";

Create a pattern object by compiling the regular expression pattern using the Pattern.compile() as shown below.

Pattern regex = Pattern.compile(pattern);

To perform matching operations on a given input string, we need to create a Matcher object by calling the matcher() method using the Pattern object and passing the larger string as an argument as shown below.

Matcher matcher = regex.matcher(inputString);

Finally, perform the substring match using the find() method of the Matcher class. This method returns the boolean value which indicates whether the substring is found or not.

if (matcher.find()) {
    // Substring found
    // Access the matched substring using matcher.group()
} else {
    // Substring not found
}

Following is the complete example:

import java.util.regex.*;

public class SubstringSearchExample {
    public static void main(String[] args) {
        String inputString = "I have car and a bike";
        String pattern = "car";

        // Create the Pattern object
        Pattern regex = Pattern.compile(pattern);

        // Create the Matcher object
        Matcher matcher = regex.matcher(inputString);

        // Perform the substring search
        if (matcher.find()) {
            String matchedSubstring = matcher.group();
            System.out.println("Substring found: " + matchedSubstring);
        } else {
            System.out.println("Substring not found");
        }
    }
}

Categorized in:

Tagged in: