我的.srt文件内容如下:
1
00:00:00,000 - > 00:00:01,000
这是第一行:
它有一个辅助线,
它可能有更多行
2
00:00:01,000 - > 00:00:02000
这是第二行
它可能有更多的线
3
00:00:02,000 - > 00:00:03,000
这是最后一行
它也有一个辅助线,
它可能有更多行
我正在使用扫描仪,但未正确解析如下:
var indexString: NSString?
scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &indexString)
var startTimeString: NSString?
scanner.scanUpTo(" --> ", into: &startTimeString)
scanner.scanString("-->", into: nil)
var endTimeString: NSString?
scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &endTimeString)
var textString: NSString?
scanner.scanUpTo("\n", into: &textString)
if textString != nil {
textString = (textString?.replacingOccurrences(of: "\r\n", with: " "))! as NSString
textString = (textString?.trimmingCharacters(in: CharacterSet.whitespaces))! as NSString
}
答案 0 :(得分:0)
考虑使用简单的正则表达式:
let pattern = "(?<index>^\\d+$)\\n^(?<startTime>\\d\\d:[0-5]\\d:[0-5]\\d,\\d{1,3}) --> (?<endTime>\\d\\d:[0-5]\\d:[0-5]\\d,\\d{1,3})$\\n(?<text>(?:^.+$\\n?)+)"
let regex = try NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let matches = regex.matches(in: srt, range: NSRange(..<srt.endIndex, in: srt))
let firstTextRange = matches[0].range(withName: "text")
let firstText = Range(firstTextRange, in: srt).flatMap { range in String(srt[range]) }
我建议缓存正则表达式。