Vlad
Vlad

Reputation: 2565

RegEx to transform a short date pattern

I need to transform (regex, preferably) a short date pattern string into a string of a different format.

For example, if I have "dd/mm/yyyy" in the end I want to see "%d/%m/%y". Or if I have "MMMM-DD-YY", I'd like to see "%m-%d-%y". In other words, each part of the date format should be shortened to one character and prefixed with a percentage sign. The order of the parts and separators must stay the same.

Greatly appreciate any help.

Upvotes: 1

Views: 383

Answers (1)

Bryan Elliott
Bryan Elliott

Reputation: 4095

You could use this:

([\w])[\w]+([/-])([\w])[\w]+([/-])([\w])[\w]+

And replace with:

%$1$2%$3$4%$5

Working regex example:

http://regex101.com/r/vJ7dL1

C#

string example1 = "dd/mm/yyyy";
string example2 = "MMMM-DD-YY";

Regex rgx = new Regex(@"([\w])[\w]+([/-])([\w])[\w]+([/-])([\w])[\w]+");

string result1 = rgx.Replace(example1, "%$1$2%$3$4%$5");
string result2 = rgx.Replace(example2, "%$1$2%$3$4%$5");

Console.WriteLine(result1);
Console.WriteLine(result2);

Output:

%d/%m/%y
%M-%D-%Y

Note: You could use ToLower() to ensure M-D-Y was lower case.. if you want.

Upvotes: 2

Related Questions