【问题标题】:Trying to read a text file using regex to check each line尝试使用正则表达式读取文本文件以检查每一行
【发布时间】:2014-10-09 03:26:10
【问题描述】:

我正在尝试编写一个程序,允许用户输入电影的名称,然后该程序将生成与之关联的日期。我有一个包含日期和与之相关的电影的文本文件。我正在通过扫描仪读取文件,并创建了一个电影类,该类分别存储电影和日期的 ArrayList 和字符串。我在阅读文件时遇到问题。谁能帮助我。谢谢!

这是文本文件的一部分:

10/1/2014   
    Der Anstandige
    "Men, Women and Children"
    Nas: Time is Illmatic

10/2/2014   
    Bang Bang
    Haider

10/3/2014   
    Annabelle
    Bitter Honey
    Breakup Buddies
    La chambre bleue
    Drive Hard
    Gone Girl
    The Good Lie
    A Good Marriage
    The Hero of Color City
    Inner Demons
    Left Behind
    Libertador
    The Supreme Price

这是我的电影课

import java.util.ArrayList;

public class movie
{
    private ArrayList<String> movies;
    private String date;

    public movie(ArrayList<String> movies, String date)
    {
        this.movies = movies;
        this.date = date;
    }

    public String getDate()
    {
        return date;
    }

    public void setDate(String date)
    {
        this.date = date;
    }

    public ArrayList<String> getMovies()
    {
        return movies;
    }
}

这里是 readFile 类

package Read;

import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class readFile
{
    public static List<movie> movies;
    public static String realPath;
    public static ArrayList<String> mov;
    public static String j;
    public static String i;

    public static void main(String[]args)
    {
        //movies = new ArrayList<movie>();
        realPath = "movie_release_dates.txt";
        File f = new File(realPath);
        try
        {
            String regex1 = "[^(0-9).+]";
            String regex2 = "[^0-9$]";

            Scanner sc = new Scanner(f);

            while (sc.hasNextLine())
            {
                System.out.println("Hello");
                //movies
                if(!sc.nextLine().matches(regex2))
                {
                    i = sc.nextLine();
                    System.out.println("Hello2");
                    System.out.println(i);
                }
                //date
                while(sc.nextLine().matches(regex1))
                {
                    System.out.println("Hello3");
                    if(!sc.nextLine().matches(regex1))
                    {
                        j = sc.nextLine();
                        mov.add(sc.nextLine());
                        System.out.println("Hello4");
                    }
                }
                movie movie = new movie(mov,i);
                movies.add(movie);
            }

        //   sc.close();
        }
        catch(Exception e)
        {
            System.out.println("CANT");
        }
    }
}

【问题讨论】:

  • “你遇到麻烦了”是什么意思?是否抛出异常?如果是这样,什么例外,在哪里?它是在做一些意想不到的事情,还是没有做一些事情,如果是,那是什么?
  • @drewmoore 我的错,我没有得到每一行的字符串。所以问题出在我的代码上,特别是用于隔离日期并存储它的正则表达式,还隔离了该特定日期的电影列表。

标签: java regex arraylist java.util.scanner


【解决方案1】:

您不应该在每次检查中都调用 sc.nextLine ()。每个 NextLine () 调用都会读取下一行。这意味着您正在检查一行并处理下一行

【讨论】:

    【解决方案2】:
    package com.stackoverflow.q26269799;
    
    import java.util.List;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class ReadFile {
        public static List<Movie> movies = new ArrayList<Movie>();
        public static String realPath;
        public static ArrayList<String> mov;
        public static String j;
        public static String i;
    
        public static void main(String[] args) {
            //movies = new ArrayList<movie>();
            realPath = "movie_release_dates.txt";
            File f = new File(realPath);
            if ( !f.exists()) {
                System.err.println("file path not specified");
            }
            try {
                String regex1 = "[^(0-9).+]";
                String regex2 = "[^0-9$]";
    
                Scanner sc = new Scanner(f);
    
                    while (sc.hasNextLine()) {
                        System.out.println("Hello");
                        // movies
                        String nextLine = sc.nextLine();
                        if (nextLine != null) {
                            if ( !nextLine.matches(regex2)) {
                                i = nextLine;
                                System.out.println("Hello2");
                                System.out.println(i);
    
                            }
                            // date
                            while (nextLine != null && nextLine.matches(regex1)) {
                                System.out.println("Hello3");
                                if ( !nextLine.matches(regex1)) {
                                    j = nextLine;
                                    mov.add(nextLine);
                                    System.out.println("Hello4");
    
                                }                           
                                nextLine = sc.nextLine();
                            }
                        }
                        Movie movie = new Movie(mov, i);
                        movies.add(movie);
                    }   
    
                 //   sc.close();
                 } catch(Exception e) {
                      throw new RuntimeException(e);
                 }
        }
    }
    
    1. 这是必需的://movies = new ArrayList&lt;movie&gt;();
    2. 每次调用 nextLine 时,它​​都会将扫描仪点移动到下一行。所以一次调用它并检查它是否匹配那些正则表达式。 String nextLine = sc.nextLine();
    3. 请检查您是否指定了文件路径。

    【讨论】:

    • 我尝试了您的代码,但它进入了无限循环(打印 Hello3)。它与正则表达式有关吗?
    • @user3162117 在 Hello3 循环中,我不明白你的目的是什么。我使用你上面提供的 txt,代码永远不会进入这个循环。我不确定是什么输入文件导致了这个无限循环。我只是编辑代码添加“nextLine = sc.nextLine();”在循环中获取下一行,这有帮助吗?
    【解决方案3】:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.LineNumberReader;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.TreeMap;
    
    public class ReadFile
    {
        Map<String, String> movies;
    
        public static void main(String[] args) throws IOException
        {
            ReadFile readFile = new ReadFile();
    
            readFile.movies = new TreeMap<>();
    
            try
            {
                readFile.importData();
    
                printf(readFile.queryData("Der Anstandige"));
    
                printf(readFile.queryData("Bitter"));
    
                printf(readFile.queryData("blah"));
    
                printf(readFile.queryData("the"));
            }
            catch(IOException e)
            {
                throw(e);
            }
        }
    
        void importData() throws IOException, FileNotFoundException
        {
            LineNumberReader reader = null;
    
            File file = new File("c:/movie_release_dates.txt");
    
            try
            {
                reader = new LineNumberReader(new FileReader(file), 1024*64);    //
    
                String line;
    
                String date = null, movie = null;
    
                while((line = reader.readLine()) != null)
                {
                    line = line.trim();
    
                    if(line.equals("")) continue;
    
                    if(line.matches(PATTERN_DATE))
                    {
                        date = line;
                        date = strf("%s/%s", 
                                    date.substring(date.length() - 4),
                                    date.substring(0, date.length() - 5));
    
                        continue;
                    }
                    else
                    {
                        movie = line.trim();
                    }
    
                    movies.put(movie, date);
                }
            }
            catch(FileNotFoundException e)
            {
    
                throw(e);
            }
            finally
            {
                reader.close();
            }
        }
    
        String queryData(String title)
        {
            String regex = "(?i)" + title.replaceAll("\\s", "\\s+");
    
            String[] matches = new String[movies.size()];
    
            int i = 0; for(Entry<String , String> movie : movies.entrySet())
            {
                String key = movie.getKey();
                String val = movie.getValue();
    
                if(key.matches(regex))
                {
                    matches[i++] = strf("{movie=%s, date=%s}", key, val);
                }
                else if(key.toUpperCase().trim()
                           .contains(title.toUpperCase().trim()))
                {
                    matches[i++] = strf("{movie=%s, date=%s}", key, val);
                }
            }
    
            String string = "";
    
            if(matches[0] == null)
            {
                string = "Not found\n";
            }
            else
            {
                i = 0; while(matches[i] != null)
                {
                    string += matches[i++] + "\n";
                }
            }
    
            return string;
        }
    
        final String strf(String arg0, Object ... arg1)
        {
            return String.format(arg0, arg1);
        }
    
        final static void printf(String format, Object ... args)
        {
            System.out.printf(format, args);
        }
    
        final static void println(String x)
        {
            System.out.println(x);
        }
    
        final String PATTERN_DATE = "\\d{1,2}\\/\\d{1,2}\\/\\d{4}";
    }
    

    控制台输出: {movie=Der Anstandige, date=2014/10/1} {movie=Bitter Honey, date=2014/10/3} Not found {movie=The Good Lie, date=2014/10/3} {movie=The Hero of Color City, date=2014/10/3} {movie=The Supreme Price, date=2014/10/3}

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多