regex

Java Matcher find Demonstration

With this example, we are going to demonstrate how to use Java Matcher find() API method to find subsequences of an input sequence that matches a specified pattern.

1. Pattern Matcher in Java API

In this section, we will outline the steps used to create an example.

java matcher
  • A Pattern object is created, using the compile(String regex) API method of Pattern, that compiles a given regular expression to a Pattern. The regular expression here is constructed by a word character, one or more times.
  • The Pattern object is then used to create a new object that will match the given input against this pattern, using the matcher(CharSequence input) API method.
  • By invoking the find() and group() methods on the Matcher object, we do pattern matching and print subsequences of the input parameter.
  • We will show how the find(int start) method can be invoked on the object by performing pattern matching, starting from a specified index that is incremented by 1.

2. MatcherFind class

In this section we will see the implementation.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherFind {
    public static void main(String[] args) {
        Matcher matcher = Pattern.compile("\\w+").matcher(
                "Evening is full of the linnet's wings");
        while (matcher.find())
            System.out.println(matcher.group());
        int i = 0;
        while (matcher.find(i)) {
            System.out.print(matcher.group() + " ");
            i++;
        }
    }
}

This will output:

Evening
is
full
of
the
linnet
s
wings
Evening vening ening ning ing ng g is is s full full ull ll l of of f the the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s 

3. Download the Source Code

This was an example to demonstrate the use of Matcher.find() API method to find subsequences in Java.

Download
You can download the full source code of this example here: Java Matcher Find Demonstration

Last updated on Jun. 01st, 2020

Sowmya Shankar

Sowmya works as a Senior Web Applications Programmer in the higher educational sector, where she leads projects based on Java. She graduated from Anna University's Computer Sciences department, followed by a Masters degree in Computer and Information Sciences from the University of Delaware. Her project portfolio features diverse web applications using frameworks such as Struts2, Spring, Spring Boot, as well as her recent experiments in the world of Microservices and the React JS framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button