我编写了以下代码,目的是存储和显示所有以字母a开头并以z结尾的单词。首先,我从正则表达式模式中得到了一个错误,其次,由于没有显示存储在ArrayList中的内容(字符串),我得到了一个错误。

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


public class RegexSimple2{

    public static void main(String[] args) {
        try{
            Scanner myfis = new Scanner("D:\\myfis2.txt");
            ArrayList <String> foundaz = new ArrayList<String>();
            while(myfis.hasNext()){
                String line = myfis.nextLine();
                String delim = " ";
                String [] words = line.split(delim);
                 for ( String s: words){
                    if(!s.isEmpty()&& s!=null){
                        Pattern pi = Pattern.compile("[a|A][a-z]*[z]");
                        Matcher ma = pi.matcher(s);
                        boolean search = false;
                        while (ma.find()){
                            search = true;
                            foundaz.add(s);
                        }
                        if(!search){
                            System.out.println("Words that start with a and end with z have not been found");
                        }
                    }
                }
            }

            if(!foundaz.isEmpty()){
                for(String s: foundaz){
                    System.out.println("The word that start with a and ends with z is:" + s + " ");
                }
            }
        }
        catch(Exception ex){
            System.out.println(ex);
        }
    }
}

最佳答案

您需要更改读取文件的方式。此外,将正则表达式更改为[aA].*z.*匹配零个或多个。请参阅我在下面所做的较小更改:

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

public class Test {

    public static void main(String[] args) {

        try {
            BufferedReader myfis = new BufferedReader(new FileReader("D:\\myfis2.txt"));
            ArrayList<String> foundaz = new ArrayList<String>();

            String line;
            while ((line = myfis.readLine()) != null) {
                String delim = " ";
                String[] words = line.split(delim);

                for (String s : words) {
                    if (!s.isEmpty() && s != null) {
                        Pattern pi = Pattern.compile("[aA].*z");
                        Matcher ma = pi.matcher(s);

                        if (ma.find()) {
                           foundaz.add(s);
                        }
                    }
                }
            }

            if (!foundaz.isEmpty()) {
                System.out.println("The words that start with a and ends with z are:");
                for (String s : foundaz) {
                    System.out.println(s);
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


输入为:

apple
applez
Applez
banana


输出为:

The words that start with a and ends with z are:
applez
Applez

09-30 17:42
查看更多