user2814753
user2814753

Reputation: 21

Replacing Date within string Regex

I am not very good with regex and am having difficult understanding how to implement it to solve my problem.
Basically I have a file name which will feature today's date in its name and I would like to replace it with yesterdays date.

var fName = "XX_YYYYYYYYYY_ZZZZZZ_2013-09-25_QQQQQ_IIII.xml";

I need to replace the part 2013-09-24 so that the new file name would be

XX_YYYYYYYYYY_ZZZZZZ_2013-09-24_QQQQQ_IIII.xml

This is how I formated the date:

String dateToday = String.Format("{0: yyyy-MM-dd}", DateTime.Today)
string dateLast = String.Format("{0: yyyy-MM-dd}", DateTime.Today.AddDays(-1))

Upvotes: 2

Views: 2356

Answers (2)

gpmurthy
gpmurthy

Reputation: 2427

Consider the following...

var fName = "XX_YYYYYYYYYY_ZZZZZZ_2013-09-25_QQQQQ_IIII.xml";
var newFName= Regex.Replace(fName, DateTime.Today.ToString("yyyy-MM-dd"), DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd"));

Upvotes: 1

James
James

Reputation: 82096

You don't need a regex for this, just use String.Replace e.g.

var fName = "XX_YYYYYYYYYY_ZZZZZZ_2013-09-25_QQQQQ_IIII.xml";
var newName = fName.Replace(String.Format("{0:yyyy-MM-dd}", DateTime.Today), String.Format("{0:yyyy-MM-dd}", DateTime.Today.AddDays(-i)));

You have whitespace in your formatting condition, in order for this to work you need to remove that i.e. replace {0: yyyy-MM-dd} with {0:yyyy-MM-dd}.

See this example

Upvotes: 5

Related Questions