0

I need to validate input to my application. The input is a formatted string that may contain parts of a Date, e.g.:

{0:yy}{0:MM}{0:dd}_{0:hh}{0:mm}{0:ss}-SOME OTHER TEXT
sometext{0:yyyy}{0:MM}{0:dd}mORETEXT

The input doesn't have to contain those parts of a date, but if it does, I need them to be valid format items that can be used by String.Format() method. I believe I should validate using Regular Expressions, but I am not good at it.

Could you please help?

7
  • So you're trying to parse dates out of an arbitrary string? Or are you doing assertive validation? Commented Jun 21, 2012 at 14:17
  • I am not sure what assertive validation is. I store these strings in the database, and use them in my C# code like this: FileName = String.Format(dr["FileNameTemplate"].ToString(), DateTime.UtcNow) Commented Jun 21, 2012 at 14:32
  • So I don't want the user to enter invalid format item like "SomeText{garbage}moreText{moregarbage}theend" Commented Jun 21, 2012 at 14:37
  • That sounds like parsing, then. By "assertive validation" I meant putting on the brakes and telling the user "no, that's not valid - fix it". Commented Jun 21, 2012 at 14:39
  • So if the string contains single curly brace, there must be a closing brace, and between them there must be "0:" plus a valid part of a DateTime. I mean valid to be used as a format item in C#'s String.Format() method. Commented Jun 21, 2012 at 14:40

1 Answer 1

1

Given our back-and-forth via comments, I think the what you are looking for is:

        Regex curlyThings = new Regex(@"\{0:.*?\}");
        Regex kosherCurlyThings = new Regex(@"\{0:(yy|yyyy|MM|dd|hh|mm|ss)\}");

        MatchCollection matchCollection = curlyThings.Matches("CG{0:yyyy}-{0:MM}-{0:dd}asdf{0:GARBAGE}.csv");
        foreach(Match match in matchCollection)
        {
            if(!kosherCurlyThings.IsMatch(match.Value))
            {
                Console.WriteLine("{0} isn't kosher!", match.Value);
            }                
        }
Sign up to request clarification or add additional context in comments.

16 Comments

You probably want to escape { and } characters since they're special characters in regexes.
@jonnyGold Hmmm... Something goes wrong. I tried to test this with the following code:
var r = new Regex(@".*?(\{0:yy(yy)?\}\{0:MM\}\{0:dd\}(_\{0:hh\}\{0:mm\}\{0:ss\}))?.*?"); if (!r.IsMatch("CG{0:yyyGARBAGEy}-{0:MM}-{0:dd}.csv")) { var blah = "The format is invalid!"; }
But it my bad string was found valid... Am I doing something wrong?
I just thought of a better answer that should work... take a look.
|

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.