regex

Matcher start example

In this example we shall show you how to use Matcher.start() API method to get the start index of the previous match of a sequence against a pattern. To use Matcher.start() one should perform the following steps:

  • Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern.
  • Use an initial String to be matched against the Pattern.
  • Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
  • Find the next subsequence of the input sequence that matches the pattern it returns it, using find() API method of Matcher.
  • Get the start index of the first match, with start() API method of Matcher.
  • Find the next subsequence, and again the start index of the second match.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

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

public class MatcherStart {

    public static void main(String args[]) {

  

  String str = "My name is Bond. James Bond.";

  String mHelp[] = {"
    ^", "


    ^"};

  Pattern pattern = Pattern.compile("Bond");

  Matcher m = pattern.matcher(str);


  //Find the starting point of the first 'Bond'

  m.find();

  int sIndex = m.start();

  System.out.println(str);

  System.out.println(mHelp[0] + sIndex);


  //Find the starting point of the second 'Bond'

  m.find();

  int nIndex = m.start();

  System.out.println(str);

  System.out.println(mHelp[1] + nIndex);

    }
}

Output:

My name is Bond. James Bond.



^11
My name is Bond. James Bond.



    ^23

 
This was an example of Matcher.start() API method in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
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