Zabi
Zabi

Reputation: 1369

C# Regex Help replacing patterns

I'm not really good at regex (I only get to use it a few times a year) and want to see if someone can help with a C# regex statement which finds all instances of

<####-##-##> or </####-##-##>

and replaces it with

<date-####-##-##> or </date-####-##-##>

so that

<2012-01-01>stuff</2012-01-01><2012-05-01>stuff2</2012-05-01>

becomes

<date-2012-01-01>stuff</date-2012-01-01><date-2012-05-01>stuff2</date-2012-05-01>

Upvotes: 1

Views: 142

Answers (2)

speti43
speti43

Reputation: 3046

If you examine the values inside tags this would be a solution.

if(Regex.IsMatch(input, @"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$"))
        {
            input.Replace(input,"date-"+input);
        }

Upvotes: 0

Anders Arpi
Anders Arpi

Reputation: 8417

string test = "<2012-01-01>stuff</2012-01-01><2012-05-01>stuff2</2012-05-01>";

var regex = new Regex(@"<(/?)(\d\d\d\d)-(\d\d)-(\d\d)>");
var result = regex.Replace(test, @"<$1date-$2-$3-$4>");

Console.WriteLine(result);

//output:
//<date-2012-01-01>stuff</date-2012-01-01><date-2012-05-01>stuff2</date-2012-05-01>

Note that the need for detail goes up depending on the other text in the strings your are processing. Are there lots of other tags? Numbers that aren't dates? etc..

Upvotes: 1

Related Questions