Using regular expressions in C# to adjust the width & height of an embedded YouTube movie

In order to get a YouTube movie to nicely fit in the page layout, i had to change the width and height properties in the default YouTube embed-code.

Here’s the code that did the job:

string youTubeObjectEmbedCode = "<object width=\"425\" height=\"349\"><param name=\"movie\" value=\"\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"425\" height=\"349\"></embed></object>";

Regex YoutubeEmbedCodeAdjuster = new Regex("((?<front>(?<attrib>width|height)(\\=)(\\\"))(?<size>[0-9]{1,})(?<back>\\\"))", RegexOptions.IgnoreCase);

MatchEvaluator SizeReplacer = new MatchEvaluator(ReplaceSize);

newYouTubeObjectEmbedCode = YoutubeEmbedCodeAdjuster.Replace(youTubeObjectEmbedCode, SizeReplacer);

    public string ReplaceSize(Match m)
        int newsize = 0;

        if (m.Groups["attrib"].Value.ToLower() == "width")
            newsize = 490;
            newsize = 396;

        return m.Groups["front"].Value + newsize + m.Groups["back"].Value;

New version of the regular expression to find all attributes



No comments yet.

Sorry, the comment form is closed at this time.