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);
    }
}


在上面的代码中,当我输入ab时,它的位置显示为0.但是也显示了异常。我需要像我输入ab这样的输出,它应该显示ab。如果我输入其他类似def的内容,则必须显示异常。你能帮我么?

最佳答案

这是更改的方法:

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");
    }

}

07-26 09:27