Skip to content

Instantly share code, notes, and snippets.

@alwarren
Created April 4, 2019 19:59
Show Gist options
  • Save alwarren/34ed39c35189cb0c35aa9c2edb8fe17e to your computer and use it in GitHub Desktop.
Save alwarren/34ed39c35189cb0c35aa9c2edb8fe17e to your computer and use it in GitHub Desktop.
Parse an SRT File (single line subtitles) [Kotlin]
import java.io.File
import java.nio.charset.Charset
class SrtFile(private val file: File, private val defaultCharset: Charset = Charset.forName("UTF-8")) {
private val _subtitles by lazy { parse() }
val subtitles: List<Subtitle> get() = _subtitles
private fun parse(): MutableList<Subtitle> {
val list = mutableListOf<Subtitle>()
var id = ""
var timeCode = ""
var content = ""
file.readLines(defaultCharset).let { lines ->
lines.forEach { value ->
when(value.type) {
Matches.Id -> id = value
Matches.TimeCode -> timeCode = value
Matches.Content -> {
content = value
list.add(Subtitle(id, timeCode, content))
id = ""
timeCode = ""
content = ""
}
}
}
}
return list
}
data class Subtitle(val id: String, val timeCode: String, val text: String)
private sealed class Matches {
object Content: Matches()
object TimeCode: Matches()
object Id: Matches()
object None: Matches()
}
private val String.type: Matches get() {
val id = "^\\d+\$".toRegex()
val timeCode = "([\\d]{2}:[\\d]{2}:[\\d]{2},[\\d]{3}).*([\\d]{2}:[\\d]{2}:[\\d]{2},[\\d]{3})".toRegex()
val content = "^[a-zA-Z].*".toRegex()
return when {
matches(id) -> Matches.Id
matches(timeCode) -> Matches.TimeCode
matches(content) -> Matches.Content
else -> Matches.None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment