1

I have string. "12341234115151_log_1.txt" (this string length is not fixed. but "log" pattern always same) I have a for loop. each iteration, I want to set the number after "log" of i.

like "12341234115151_log_2.txt" "12341234115151_log_3.txt" ....

to "12341234115151_log_123.txt"

in c#, what is a good way to do so? thanks.

2
  • Sounds like a perfect job for regular expression: \d+_log_(\d+).txt Commented Nov 11, 2011 at 1:36
  • So you want to make the log files look like this: 12341234115151_log_1.txt,12341234115151_log_12.txt, 12341234115151_log_123.txt, 12341234115151_log_1234.txt etc? Commented Nov 11, 2011 at 1:37

4 Answers 4

1

A regex is ideal for this. You can use the Regex.Replace method and use a MatchEvaluator delegate to perform the numerical increment.

string input = "12341234115151_log_1.txt";
string pattern = @"(\d+)(?=\.)";
string result = Regex.Replace(input, pattern,
    m => (int.Parse(m.Groups[1].Value) + 1).ToString());

The pattern breakdown is as follows:

  • (\d+): this matches and captures any digit, at least once
  • (?=\.): this is a look-ahead which ensures that a period (or dot) follows the number. A dot must be escaped to be a literal dot instead of a regex metacharacter. We know that the value you want to increment is right before the ".txt" so it should always have a dot after it. You could also use (?=\.txt) to make it clearer and be explicit, but you may have to use RegexOptions.IgnoreCase if your filename extension can have different cases.
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Regex. like this

    var r = new Regex("^(.*_log_)(\\d).txt$")
    for ... {

        var newname = r.Replace(filename, "${1}"+i+".txt");
    }

Comments

0

Use regular expressions to get the counter, then just append them together.

If I've read your question right...

Comments

0

How about,

for (int i =0; i<some condition; i++)
{
  string name = "12341234115151_log_"+ i.ToString() + ".txt";
}

Comments

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.