[英]Validating input with Regex
我需要驗證輸入到我的應用程序。 輸入是一個格式化的字符串,其中可能包含日期的一部分,例如:
{0:yy}{0:MM}{0:dd}_{0:hh}{0:mm}{0:ss}-SOME OTHER TEXT
sometext{0:yyyy}{0:MM}{0:dd}mORETEXT
輸入不必包含日期的那些部分,但是如果包含,我需要它們是可以由String.Format()
方法使用的有效格式項。 我相信我應該使用Regular Expressions
進行驗證,但是我並不擅長於此。
能否請你幫忙?
考慮到我們的來回評論,我認為您正在尋找的是:
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.