Click here to Skip to main content
15,798,151 members
Articles / Programming Languages / C#

Subtitle Synchronization with C#

Rate me:
Please Sign up or sign in to vote.
4.67/5 (12 votes)
26 Jan 2009CPOL2 min read 52.1K   2K   24   8
Demonstrates regular expression use for subtitles synchronization


This article shows an example of text file manipulation techniques and regular expression use for subtitle synchronization.


Yesterday I watched "P.S. I love you", and I love it (no pun intended). I downloaded it and came across a subtitle file with correct translation, but it was out-of-sync. So I started to write a small program to fix that.

In my research, I found nice programs to do that, but it was early Sunday and I had nothing better to do. You know how it ends.

Using the Code

This is a console application which receives a filename. I expect that to be a regular .SRT (SubRip) file, so it's a text file with the following structure:

00:16:38,731 --> 00:16:41,325
<i>Happy Christmas, your arse
I pray God it's our last</i>

So we have a sequential number, start and end time for display and the text; those blocks are separated by an empty line. In my case, I just wanted to add a time offset.

I start creating a regular expression for that pattern:

private static Regex unit = new Regex(
   @"(?<sequence>\d+)\r\n(?<start>\d{2}\:\d{2}\:\d{2},\d{3}) --\> " + 
   RegexOptions.Compiled | RegexOptions.ECMAScript);

I used named matches (?<name>) to identify the relevant parts from text units, so we can read:

  • the text unit sequence, as one or more numbers, and a line break
  • start and end time, formatted as HH:mm:ss,fff, and a line break
  • legend text and the end of that block (two consecutive line breaks)

Believe me, that's the "hardest" part. Let's ask for time offset:

double offset = 0;
Console.Write("offset, in seconds (+1.1, -2.75): ");
while (!Double.TryParse(Console.ReadLine(), out offset))
    Console.WriteLine("Invalid value, try again");

Note the Double.TryParse. As you probably can imagine, it's trying to parse a string into a double value, but don't throw exceptions. It's very useful when you ask for input values and can speed up the code execution.

Now we just need to read one file and write another one.

using (StreamReader input = new StreamReader(args[0], Encoding.Default))
    using (StreamWriter output = 
       new StreamWriter(args[0] + ".srt", false, Encoding.Default))
            unit.Replace(input.ReadToEnd(), delegate(Match m)
                return m.Value.Replace(
                    String.Format("{0}\r\n{1} --> {2}\r\n",
                        m.Groups["start"   ].Value,
                        m.Groups["end"     ].Value),
                        "{0}\r\n{1:HH\\:mm\\:ss\\,fff} --> " + 
                        DateTime.Parse(m.Groups["end"  ].Value.Replace(",","."))

So, read an entire input file into memory and replace, one unit at time, the original time by new ones, adding the offset. Write everything in the output file and you are good to go.

Points of Interest

The most interesting part was the time offset formatting. Seems .SRT file format uses a comma as milliseconds separator, so I spent another replace inside the MatchEvaluator delegate to fix that.

Another point was the file encoding. The trick was to define the encoding as default and make sure it was the same output file encoding, so the accents could be correctly preserved.

Besides that, this program ran correctly in the first use.


  • 1.0: Initial version
  • 1.1: Fixed some typos and added some external links


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
Brazil Brazil
Brazilian developer and freelancer. Currently interested in programming frameworks, code generation and development productivity.

Comments and Discussions

QuestionRead Specific Line of Srt file With İndex Pin
Umut Comlekcioglu5-May-15 21:56
professionalUmut Comlekcioglu5-May-15 21:56 
SuggestionEncoding Pin
Ivandro Ismael15-Jan-14 22:12
Ivandro Ismael15-Jan-14 22:12 
QuestionGreat Article Pin
Ha-Ahmadi9-Aug-13 7:58
Ha-Ahmadi9-Aug-13 7:58 
AnswerRe: Great Article Pin
Ivandro Ismael15-Jan-14 22:14
Ivandro Ismael15-Jan-14 22:14 
GeneralMisc note, regarding decimal separator Pin
_groo_26-Jan-09 22:15
_groo_26-Jan-09 22:15 
AnswerRe: Misc note, regarding decimal separator Pin
RubensFarias27-Jan-09 12:39
RubensFarias27-Jan-09 12:39 
GeneralRe: Misc note, regarding decimal separator Pin
_groo_7-Apr-09 4:15
_groo_7-Apr-09 4:15 
GeneralRe: Misc note, regarding decimal separator Pin
RubensFarias7-Apr-09 14:22
RubensFarias7-Apr-09 14:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.