有没有什么办法来搜索字符串的模式在C#?
Is there any way to search patterns in strings in C#?
东西,如SQL LIKE将是非常有益的。
Something like Sql LIKE would be very useful.
普通EX pressions允许的一切, LIKE
允许,等等,但一个完全不同的语法。然而,由于规则 LIKE
是如此简单(其中%
表示零或更多的字符和 _
表示一个字符),无一不 LIKE
参数,并定期EX pressions是pssed在字符串中的前$ P $,我们可以创建一个普通的前pression,需要一个 LIKE
参数(如 abc_ef%*美元
),并把它成等价的普通恩pression(如 Aabc.ef. * * USD Z
):
Regular expressions allow for everything that LIKE
allows for, and much more, but have a completely different syntax. However, since the rules for LIKE
are so simple(where %
means zero-or-more characters and _
means one character), and both LIKE
arguments and regular expressions are expressed in strings, we can create a regular expression that takes a LIKE
argument (e.g. abc_ef% *usd
) and turn it into the equivalent regular expression (e.g. Aabc.ef.* *usdz
):
@"A" + new Regex(@".|$|^|{|[|(|||)|*|+|?|\").Replace(toFind, ch => @"" + ch).Replace('_', '.').Replace("%", ".*") + @"z"
这是我们可以建立一个赞()
方法:
From that we can build a Like()
method:
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);
}
}
因此:
bool willBeTrue = "abcdefg".Like("abcd_fg");
bool willAlsoBeTrue = "abcdefg".Like("ab%f%");
bool willBeFalse = "abcdefghi".Like("abcd_fg");
上一篇:如何检查是否该应用程序的另一实例正在运行应用程序、实例、正在运行
下一篇:ASP.net收到错误"对路径的访问被拒绝&QUOT。而试图将文件上传到我的Windows Server 2008 R2的Web服务器到我、路径、文件上传、被拒