Home »
Java »
Java Programs
Java program to search a pattern into the string using regular expression
Given a string, we have to search a pattern using regular expression.
Submitted by Nidhi, on June 12, 2022
Problem statement
In this program, we will create a string and search for a pattern in the string using regular expression. Here, we used the compile() method of the Pattern class.
Source Code
The source code to search a pattern into the string using regular expression is given below. The given program is compiled and executed successfully.
// Java program to search a pattern into the string
// using regular expression
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String str = "This is a string.";
String regex = ".*is.*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
boolean result = matcher.matches();
if (result)
System.out.println("Pattern matched in string.");
else
System.out.println("Pattern did not match in string.");
}
}
Output
Pattern matched in string.
Explanation
In the above program, we imported the "java.util.regex.*" package to use the Pattern and Matcher classes. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created a string str, initialized with "This is a string". Then we used the compile() and matcher() methods to search the pattern in the string and printed the appropriate message.
Java Regular Expressions Programs »