Regex 101 Exercise S6 – Change the extension on a file

Regex 101 Exercise S6 – Change the extension on a file

Given a filename including path, change the extension to .out.

Input string example: 



  1. The best answer to this is really to use System.IO.Path.ChangeExtension(), but that wouldn’t be much of a Regex exercise, now would it?

  2. It’s not as simple as it looks

Comments (14)

  1. Hasani says:

    Regex.Replace(@"C:utilityProcessor.cs", @"[^.]+.([^.]+)$", "vb")

  2. Hasani says:

    whoops! forgot to include the path

    Regex.Replace(@"C:utilityProcessor.cs", @"(?<path>[^.]+.)[^.]+$", @"${path}vb")

  3. Hasani says:

    and apparently I can’t read.

    Regex.Replace(@"C:utilityProcessor.cs", @"(?<path>[^.]+.)[^.]+$", @"${path}out")

  4. Jay R. Wren says:

    I like:

    Regex.Replace(filename, @".(.*?)$", "out");

  5. Sachin says:


  6. Sachin says:

    slightly trimmed down version of the above regex:


    input: c:xyzabc.exe.config

    output: c:xyzabc.exe.out


  7. I assume that the regex should work regardless of the number of .s in the path. No problem there.

    But… can I assume that there is at least one dot in the filename proper? (not including the path.)

    Can I also assume that the last character is not a dot?

    If so…

    string DotOutIfy(string sFileName)


    __ // easy to read

    __ return Regex.Replace(sFileName, ".(.+)", ".out", RegexOptions.RightToLeft);

    __ // perhaps more accurate

    __ return Regex.Replace(sFileName, ".([^.\]+)$", ".out");


    If I can’t assume those things, I should check for them and raise an appropriate error.

  8. What is "expected behavior" if there is a FOLDER named



    I assume that this is the caller’s problem, not the DotOutIfy function’s problem…

  9. Reggifier says:

    (@".([^.]+)$, ".out")

  10. Hmmm… it seems that Regex.Replace(string, string, string, regexoptions) will check the entire string for all occurrences of the pattern (in a "s///g" sense, not a "1 while s///" sense) so my initial submission is wrong.

    There’s a Regex.Replace signature that allows specifying a maximum number of replacements… but no signature that allows BOTH specifying a number of replacements AND RegexOptions.RightToLeft…

    It’s beginning to seem to me that perhaps .NET regexes are not suited to this.

    If this was perl it would be easy:

    $fileName =~ s/.([^\.]+)$/.out/; # no /g

    But there’s no simple .NET regex equivalent.

    Perhaps it would be better to find the index of the last . in the string (n), take the left (n – 1) characters of the string, and add ".out"

  11. vascov says:

    Replace( filename, @".(^.)*$", "out" );

  12. Vasco Veiga says:

    oops, it should be ".[^.]*$"

    ( next time i’ll actually test the regex before posting 🙂 )

Skip to main content