Skip to content
Advertisement

parsing a .srt file with regex

I am doing a small script in python, but since I am quite new I got stuck in one part: I need to get timing and text from a .srt file. For example, from

JavaScript

I need to get:

00:00:01,000 --> 00:00:04,074

and

Subtitles downloaded from www.OpenSubtitles.org.

I have already managed to make the regex for timing, but i am stuck for the text. I’ve tried to use look behind where I use my regex for timing:

JavaScript

but with no effect. Personally, i think that using look behind is the right way to solve this, but i am not sure how to write it correctly. Can anyone help me? Thanks.

Advertisement

Answer

Honestly, I don’t see any reason to throw regex at this problem. .srt files are highly structured. The structure goes like:

  • an integer starting at 1, monotonically increasing
  • start –> stop timing
  • one or more lines of subtitle content
  • a blank line

… and repeat. Note the bold part – you might have to capture 1, 2, or 20 lines of subtitle content after the time code.

So, just take advantage of the structure. In this way you can parse everything in just one pass, without needing to put more than one line into memory at a time and still keeping all the information for each subtitle together.

JavaScript

For example, using the example on the SRT doc page, I get:

JavaScript

And I could further transform that into a list of meaningful objects:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement