Sunday 2 November 2014

find() : Find all the matches in the input

public boolean find()
The find method scans the input sequence looking for the next subsequence that matches the pattern.

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