1

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>

2 Answers 2

1
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..

Sign up to request clarification or add additional context in comments.

Comments

0

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);
        }

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.