1

尝试在此代码中解析 srt 字幕:

public class MatchArray {

public static void main(String args[]) {

    File file = new File(
            "C:/Users/Thiago/workspace/SubRegex/src/Dirty Harry VOST - Clint Eastwood.srt");
    {

        try {
            Scanner in = new Scanner(file);

            try {
                String contents = in.nextLine();

                while (in.hasNextLine()) {
                    contents = contents + "\n" + in.nextLine();
                }



                String pattern = "([\\d]+)\r([\\d]{2}:[\\d]{2}:[\\d]{2}),([\\d]{3})[\\s]*-->[\\s]*([\\d]{2}:[\\d]{2}:[\\d]{2}),([\\d]{3})\r(([^|\r]+(\r|$))+)";


                Pattern r = Pattern.compile(pattern);

                // Now create matcher object.
                Matcher m = r.matcher(contents);

                ArrayList<String> start = new ArrayList<String>();
                while (m.find()) {
                    start.add(m.group(1));
                    start.add(m.group(2));
                    start.add(m.group(3));
                    start.add(m.group(4));
                    start.add(m.group(5));
                    start.add(m.group(6));
                    start.add(m.group(7));


                    System.out.println(start);

                }
            }

            finally {
                in.close();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但是当我执行它时,它不会捕获任何组,当尝试仅捕获具有这种模式的时间时:

([\\d]{2}:[\\d]{2}:[\\d]{2}),([\\d]{3})[\\s]*-->[\\s]*([\\d]{2}:[\\d]{2}:[\\d]{2}),([\\d]{3})

有用。那么如何让它捕获整个字幕呢?

4

1 回答 1

0

我不太了解您的需求,但我认为这会有所帮助。请尝试正则表达式:

(\\d+?)\\s*(\\d+?:\\d+?:\\d+?,\\d+?)\\s+-->\\s+(\\d+?:\\d+?:\\d+?,\\d+?)\\s+(.+)

我在http://www.myregextester.com/index.php上试过它,它奏效了。

我希望这会有所帮助。

于 2013-10-01T22:02:27.593 回答