In Java, regular expressions (regex) are used to search, match, and manipulate strings based on specific patterns. The Pattern class is used to compile a regex pattern, and the Matcher class helps in finding occurrences of that pattern within a string.
By looping through the matches, we can extract and count each occurrence that matches the regex pattern. Following is an example code to find number of occurrences and matching position:
Example Code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
// Input text
String text = “The rain in Spain falls mainly in the plain.”;
// Regex pattern to find "ain"
String regex = "ain";
// Compile regex pattern
Pattern pattern = Pattern.compile(regex);
// Create matcher for the input text
Matcher matcher = pattern.matcher(text);
int count = 0;
// Loop through all matches
while (matcher.find()) {
count++;
System.out.println("Match " + count + ": \"" + matcher.group() + "\" found at index "
+ matcher.start());
}
System.out.println("Total Matches: " + count);
}
}