Search code examples
c#regexstring-interpolation

Use String.Format to create regular expression


Essentially I have a string for interpolation: Log_{0}.txt and the {0} is replaced with an integer during a different process. So the results could be something like Log_123.txt or Log_53623432.txt.

I'm trying to use string.Format() and replace {0} with a regular expression that checks for numbers. Eventually I want to be able to pull those numbers out as well.

I've tried a few different variations on something like this, but I haven't had any luck:

var stringFormat = new Regex(string.Format("Log_{0}.txt", @"^\d$"));

Also, here's the code that's checking the format:

        var fileNameFormat = new Regex(string.Format("Log_{0}.txt", @"^\d+$"));

        var existingFiles = Directory.GetFiles("c:\\projects\\something");

        foreach(var file in existingFiles)
        {
            var fileName = Path.GetFileName(file);
            if(fileNameFormat.Match(fileName).Success)
            {
                // do something here
            }              
        }

Solution

  • Problem is in your regex. ^ asserts start of the line and $ end of the line. Just replace it with @"\d+" and it should work.

    Optionally you can use new Regex(string.Format("^Log_{0}.txt$", @"\d+")); to ensure that no files such as asdffff_Log_13255.txt.temp are matched.