0

I have a string 01-Jan-2014 00:00:00 and I intend to shorten the year into 2 characters.

my code:

DateTime dtParsedDate = new DateTime();
string strInput = "01-Jan-2014 00:00:00";
Regex regDate = new Regex(@"\d{2}-\w{3}-\d{4}");

// parse into datetime object
dtParsedDate = DateTime.ParseExact(regDate.Match(strInput).Value, "dd-MMM-yyyy", CultureInfo.InvariantCulture);

// replace the string with new format
regDate.Replace(arrData[iCol], dtParsedDate.ToString("dd-MMM-yy"));

I've verified that the string is matched correctly using regex.

"01-Jan-2014" did not get replaced into "01-Jan-14". What is wrong with my code?

1
  • 2
    Read the docs. Regex.Replace returns a new string, it does not mutate the string you pass in to it (because strings are immutable). Commented Apr 29, 2014 at 13:31

2 Answers 2

2

Regex.Replace and String.Replace do not modify the existing string: they return the modified string. Try changing your code to:

arrData[iCol] = regDate.Replace(arrData[iCol], dtParsedDate.ToString("dd-MMM-yy"));
Sign up to request clarification or add additional context in comments.

Comments

2

In .NET strings are immutable and all replace methods do not replace in-place but return a new string with the replacements done.

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.