How to find matches in string using regular expression

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);
}

}

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x