我正在尝试使用javascript解析srt文件。 我从stackoverflow找到了一些代码,但是有一个问题。 我正在逐行解析srt文件,以识别字幕,时间和字幕文本的行。 但是,当代码读取字幕文本时,我的代码仅能读取一行字幕的每一行,而部分字幕包含两行或两行。
这是我的代码
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
答案 0 :(得分:0)
在此行中,您会找到常见的换行字符,并用\n
换行替换它们。
f = f.replace(/\r\n|\r|\n/g, '\n')
您需要对其进行修改,以用新的换行符替换HTML换行符<br>
。
例如:
f = f.replace(/\r\n|\r|\n|<br>/g, '\n')