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.
A regex is ideal for this. You can use the
Regex.Replacemethod and use aMatchEvaluatordelegate to perform the numerical increment.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 useRegexOptions.IgnoreCaseif your filename extension can have different cases.