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.
- A
Pattern
object is created, using thecompile(String regex)
API method of Pattern, that compiles a given regular expression to aPattern
. 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 thematcher(CharSequence input)
API method. - By invoking the
find()
andgroup()
methods on theMatcher
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
You can download the full source code of this example here: Java Matcher Find Demonstration
Last updated on Jun. 01st, 2020