1

我正在尝试使用 javascript 解析 srt 文件。我从 stackoverflow 中找到了一些代码,但有一个问题。我正在逐行解析 srt 文件以识别字幕、时间和字幕文本的行。但是当代码读取字幕文本时,我的代码每个部分只能读取一行字幕,而字幕的某些部分包含 2 行或某行。

这是我的代码

var PF_SRT = function() {
                  //SRT format
                  var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm;
                  var _regExp;

                  var init = function() {
                    _regExp = new RegExp(pattern);
                  };
                  var parse = function(f) {
                    if (typeof(f) != "string")
                      throw "Sorry, Parser accept string only.";

                    var result = [];
                    if (f == null)
                      return _subtitles;


                    f = f.replace(/\r\n|\r|\n/g, '\n')


                    while ((matches = pattern.exec(f)) != null) {
                      result.push(toLineObj(matches));
                    }

                    return result;
                  }
                  var toLineObj = function(group) {
                    var hms_start = group[2].replace(',', ':').split(':');   

                    var hms_end = group[3].replace(',', ':').split(':');   

                    return {
                      line: group[1],
                      startTime: (+hms_start[0]) * 60 * 60 + (+hms_start[1]) * 60 + (+hms_start[2]) +'.'+ hms_start[3],
                      endTime: (+hms_end[0]) * 60 * 60 + (+hms_end[1]) * 60 + (+hms_end[2]) +'.'+ hms_end[3],
                      text: group[4]
                    };
                  }
                  init();
                  return {
                    parse: parse
                  }
                }();

// execution
// result is the entire line of srt subtitle file
PF_SRT.parse(result);

我期望的输出

6
00:00:32,616 --> 00:00:41,496
{\a2}{\c&HFFFFFF&}{\fnTahoma} And 23 of them say forget it
you say this thing never worked 
because there's no such thing called internet in the world

6
00:00:32,616 --> 00:00:41,496
{\a2}{\c&HFFFFFF&}{\fnTahoma} And 23 of them say forget it<br>you say this thing never worked<br>because there's no such thing called internet in the world
4

1 回答 1

1

使用此行,您可以找到常见的换行符并将它们替换为\n新行。

f = f.replace(/\r\n|\r|\n/g, '\n')

您需要对其进行修改以将 HTML 换行符替换为换行符<br>

例如:

f = f.replace(/\r\n|\r|\n|<br>/g, '\n')
于 2019-05-13T07:14:15.490 回答