user99322
user99322

Reputation: 1207

Format string using RegEx

String to be formatted

"new Date(2009,0,1)"

String after formatting

"'01-Jan-2009'"

Upvotes: 0

Views: 1248

Answers (2)

SLaks
SLaks

Reputation: 887195

You should use the DateTime structure:

DateTime date = DateTime.Parse(something);
string str = date.ToString("dd-MMM-yyyy");

In your case, you should use a regular expression to parse the values out of the string, like this:

static readonly Regex parser = new Regex(@"new Date\((\d{4}),\s*(\d\d?),\s*(\d\d?)\)");

Match match = parser.Match("new Date(2009,0,1)");

DateTime date = new DateTime(
    int.Parse(match.Groups[1].Value),
    int.Parse(match.Groups[2].Value) + 1,
    int.Parse(match.Groups[3].Value)
);

string str = date.ToString("dd-MMM-yyyy");

(Tested)

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

You can't use a regex for this - you can only work with existing text. Adding new characters (Jan instead of 1 (or 0??)) is not possible.

What you can do is match @"new Date\((\d+),(\+d),(\d+)\). Then you'll have three strings containing 2009, 0, and 1 in the Match object's groups 1, 2, and 3.

Upvotes: 1

Related Questions