views:

20

answers:

1
import java.util.regex.*;
import java.io.*;
class Patmatch{

    static String str = "";

    public static void main(String[] args){
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter name to see match");
        try{

            str = br.readLine();
        } catch(IOException e){
            System.out.println("Exception has been occurred" + e);

        }

        try{
            Patternmatch();
        } catch(NomatchException me){
            System.out.println("Exception" + me);
        }
    }

    private static void Patternmatch() throws NomatchException{

        Pattern p = Pattern.compile("ab");
        Matcher m = p.matcher(str);
        while(m.find())
            System.out.print(m.start() + " ");

        throw new NomatchException("no match");

    }
}

class NomatchException extends Exception{

    NomatchException(String s){
        super(s);
    }
}

In the above code when i enter ab it shows the position exaclty as 0.But is also shows exception. I need output like if i enter ab it should show ab. if i enter something else like def it must show exception. Can you please help me?

+1  A: 

Here's the changed method:

private static void patternMatch() throws NomatchException{

    final Pattern p = Pattern.compile("ab");
    final Matcher m = p.matcher(str);

    if(m.find()){
        System.out.print(m.group());
    } else{
        throw new NomatchException("no match");
    }

}
seanizer