Home »
Java »
Java Programs
Java program to find the start and end indices for all occurrences of pattern in the string using regular expression
Given a string, we have to find the start and end indices for all occurrences of pattern in the string using regular expression.
Submitted by Nidhi, on June 13, 2022
Problem statement
In this program, we will create a string and a regular expression pattern. Then we will find the start and end indices for all occurrences of pattern in the string using the find(), start(), end() methods.
Source Code
The source code to find the start and end indices for all occurrences of pattern in the string using regular expression is given below. The given program is compiled and executed successfully.
// Java program to find the start and end indices for all occurrences
// of pattern in the string using regular expression
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String str = "bcd abc xyz abc pqr lmn";
String regex = "abc";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("Start Index: " + matcher.start() + ", End Index: " + (matcher.end() - 1));
}
}
}
Output
Start Index: 4, End Index: 6
Start Index: 12, End Index: 14
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 and pattern. Then we used the find(), start(), end() methods to find the start and end indices for all occurrences of pattern in string and printed the result.
Java Regular Expressions Programs »