Saturday 1 November 2014

Pattern class

Pattern class provides useful methods to search for a regular expression in given string. To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.

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;
                
        while(true){
            try{
                System.out.println("Enter Regular Expression");
                regex = br.readLine();
                pattern = Pattern.compile(regex);

                System.out.println("Enter the string to search");
                text = br.readLine();
                matcher = pattern.matcher(text);

                matcher.matches();

                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(Exception e){
                System.out.println(e);
            }
        }     
    }
}

Output
Enter Regular Expression
a*b
Enter the string to search
aaaab
I found the text aaaab starting at index 0 Ending at index 5
Enter Regular Expression

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment