Sunday 2 November 2014

Get the Matched sequence boundaries

Matcher class provides start(), end() methods to get the tart index of this matcher's region and to get the offset after the last character matched respectively.

public int end()
Returns the offset after the last character matched.

public int start()
Returns the start index of the previous match.

import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                while(matcher.find()){
                    System.out.print("I found the text " + matcher.group());
                    System.out.print(" starting at index " + matcher.start());
                    System.out.println(" Ending at index " + matcher.end());
                }
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
is
Enter the string
this is easy task... is it?
I found the text is starting at index 2 Ending at index 4
I found the text is starting at index 5 Ending at index 7
I found the text is starting at index 21 Ending at index 23




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment