我有两个字符串用于比较
String Str1 = "A C";
String Str2 = "A B C";
Str2.Contains(Str1); //It will return False ,Contains append % at Start and End of string
//Replace space with %
Str1 = "%A%C%";
Str2 = "%A%B%C%";
Str2.Contains(Str1); //Want it to return True ,
Run Code Online (Sandbox Code Playgroud)
我们确实有Contains,StartsWith,EndsWith比较的方法,但我的要求是,如果我们比较str2和str3,它应该返回True,因为它位于Str2中。
我们可以在 C# 中实现这样的行为吗?我已经在 SQL 中做到了这一点,但在 C# 中没有得到一些有用的东西。任何正则表达式等?
我建议将SQL-LIKE转换为正则表达式:
private static string LikeToRegular(string value) {
return "^" + Regex.Escape(value).Replace("_", ".").Replace("%", ".*") + "$";
}
Run Code Online (Sandbox Code Playgroud)
然后Regex照常使用:
string like = "%A%C%";
string source = "A B C";
if (Regex.IsMatch(source, LikeToRegular(like))) {
Console.Write("Matched");
}
Run Code Online (Sandbox Code Playgroud)
如果需要,您甚至可以实现扩展方法:
public class StringExtensions {
public static bool ContainsLike(this string source, string like) {
if (string.IsNullOrEmpty(source))
return false; // or throw exception if source == null
else if (string.IsNullOrEmpty(like))
return false; // or throw exception if like == null
return Regex.IsMatch(
source,
"^" + Regex.Escape(like).Replace("_", ".").Replace("%", ".*") + "$");
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以把
string like = "%A%C%";
string source = "A B C";
if (source.ContainsLike(source, like)) {
Console.Write("Matched");
}
Run Code Online (Sandbox Code Playgroud)