[英]Matching a Pattern in C#
这似乎是一个显而易见的事情,但我想知道C#中是否存在用于匹配字符串的通配符。 我想编写一个程序,以便用户可以根据数据库中的日期值搜索某些内容。 只要输入整个日期,我到目前为止工作,但进入半个日期会导致解析错误我现在正在使用此代码
" ... where Date like " DateTime.Parse(textbox.text.trim()) " + %;"
我想看看是否有办法看到用户输入的内容(只有年份,月份或年份没有日期,或者如果只输入半年则不会崩溃)
涉及在SQL本身中执行此操作的解决方案并不重要
解决方案1:
public static class MyStringExtensions
{
public static bool Like(this string toSearch, string toFind)
{
return new Regex(@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z", RegexOptions.Singleline).IsMatch(toSearch);
}
}
examples:
bool willBeTrue = "abcdefg".Like("abcd_fg");
bool willAlsoBeTrue = "abcdefg".Like("ab%f%");
bool willBeFalse = "abcdefghi".Like("abcd_fg");
溶液2:
madate.ToString().Contain("myvalue")
madate.ToString().StartWith("myvalue")
madate.ToString().EndWith("myvalue")
或者使用sql:其中CONVERT(VARCHAR(24),yourdate,103)就像'%yourvalue%'
where CONVERT(VARCHAR(24),yourdate, 103) like '%yourvalue%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.