如果在swift中使用Scanner包含多行字幕文本,如何解析.srt文件?

问题描述 投票:0回答:1

我的.srt文件内容如下:

1 00:00:00,000 - > 00:00:01,000 这是第一行: 它有一个辅助线, 它可能有更多的线条

2 00:00:01,000 - > 00:00:02,000 这是第二行 它可能有更多的线条

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
        }
ios swift nsscanner
1个回答
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]) }

我建议缓存正则表达式。

© www.soinside.com 2019 - 2024. All rights reserved.