2

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
            }              
        }
0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Thank you so much!
0

You forgot to put the plus + quantifier maybe?

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

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

1 Comment

Haven't had any luck with that. I updated the question with the code I'm using to check against the regex. Maybe the issue is in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.