我试图在c#中找到一个方法来返回一个通配符匹配的字符串,但是如果它包含通配符匹配,我只能找到有关如何返回的信息,而不是通配符匹配所代表的字符串。
例如,
var myString = "abcde werrty qweert";
var newStr = MyMatchFunction("a*e", myString);
//myString = "abcde"
我如何创建MyMatchFunction
?我已经在stackoverflow上搜索了一下,但是如果字符串包含通配符字符串而不是它所代表的字符串,那么与c#和wildcard有关的所有内容都只返回布尔值。
答案 0 :(得分:3)
你考虑过使用Regex吗?
例如,使用模式a.*?e
,您可以实现此效果
string sample = "abcde werrty qweert";
string pattern = "a.*?e";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(sample);
foreach (Match match in matches)
Console.WriteLine(match.Value);
哪个会打印出来
abcde
答案 1 :(得分:0)
模式为"abcde werrty qweert"
的{{1}}的通配符搜索默认值将返回"a*b"
,但您可以使用gready搜索获得"abcde werrty qwee"
的结果。
使用"abcde"
进行WildCard
匹配的功能:
Regex
结果:
public static string WildCardMatch(string wildcardPattern, string input, bool Greedy = false)
{
string regexPattern = wildcardPattern.Replace("?", ".").Replace("*", Greedy ? ".*?" : ".*");
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, regexPattern,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return m.Success ? m.Value : String.Empty;
}