Anders Lind
Anders Lind

Reputation: 4820

string in c#. replace certain number in a loop

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.

Upvotes: 1

Views: 347

Answers (4)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

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.

Upvotes: 1

Terry Ma
Terry Ma

Reputation: 369

You can use Regex. like this

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

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

Upvotes: 1

NicoTek
NicoTek

Reputation: 1167

How about,

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

Upvotes: 0

Robert
Robert

Reputation: 6540

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

If I've read your question right...

Upvotes: 0

Related Questions