Home »
Java »
Java Programs
Java program to search a pattern with case insensitive flag into the string using regular expression
Given a string, we have to search a pattern with case insensitive flag using regular expression.
Submitted by Nidhi, on June 12, 2022
Problem statement
In this program, we will create a string and search a pattern into the string using the regular expression with a case insensitive flag. Here, we used the compile() method of the Pattern class.
Source Code
The source code to search a pattern with a case insensitive flag into the string using regular expression is given below. The given program is compiled and executed successfully.
// Java program to search a pattern with flags 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, Pattern.CASE_INSENSITIVE);
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() method to search the pattern with case insensitive flag into the string and printed the appropriate message.
Java Regular Expressions Programs »