简体   繁体   English

使用正则表达式验证输入

[英]Validating input with Regex

I need to validate input to my application. 我需要验证输入到我的应用程序。 The input is a formatted string that may contain parts of a Date, eg: 输入是一个格式化的字符串,其中可能包含日期的一部分,例如:

{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. 输入不必包含日期的那些部分,但是如果包含,我需要它们是可以由String.Format()方法使用的有效格式项。 I believe I should validate using Regular Expressions , but I am not good at it. 我相信我应该使用Regular Expressions进行验证,但是我并不擅长于此。

Could you please help? 能否请你帮忙?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM