在 C# 中使用通配符搜索进行字符串比较
String comparison with Wildcard search in c#
我有两个字符串要比较
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 ,
我们确实有 Contains,StartsWith,EndsWith
比较方法,但是我的要求是,如果我们比较 str2 和 str3 ,它应该 return True ,因为它位于 Str2.
我们可以在 C# 中实现这样的行为吗?我已经在 SQL 中完成了,但在 C# 中没有得到一些有用的东西。任何 regex 等?
我建议将 SQL-LIKE 转换为 正则表达式:
private static string LikeToRegular(string value) {
return "^" + Regex.Escape(value).Replace("_", ".").Replace("%", ".*") + "$";
}
然后照常使用Regex
:
string like = "%A%C%";
string source = "A B C";
if (Regex.IsMatch(source, LikeToRegular(like))) {
Console.Write("Matched");
}
如果需要,您甚至可以实施扩展方法:
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("%", ".*") + "$");
}
}
所以你可以把
string like = "%A%C%";
string source = "A B C";
if (source.ContainsLike(source, like)) {
Console.Write("Matched");
}
我有两个字符串要比较
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 ,
我们确实有 Contains,StartsWith,EndsWith
比较方法,但是我的要求是,如果我们比较 str2 和 str3 ,它应该 return True ,因为它位于 Str2.
我们可以在 C# 中实现这样的行为吗?我已经在 SQL 中完成了,但在 C# 中没有得到一些有用的东西。任何 regex 等?
我建议将 SQL-LIKE 转换为 正则表达式:
private static string LikeToRegular(string value) {
return "^" + Regex.Escape(value).Replace("_", ".").Replace("%", ".*") + "$";
}
然后照常使用Regex
:
string like = "%A%C%";
string source = "A B C";
if (Regex.IsMatch(source, LikeToRegular(like))) {
Console.Write("Matched");
}
如果需要,您甚至可以实施扩展方法:
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("%", ".*") + "$");
}
}
所以你可以把
string like = "%A%C%";
string source = "A B C";
if (source.ContainsLike(source, like)) {
Console.Write("Matched");
}