我试图在c#中找到一个方法来返回通配符匹配的字符串,但是我只能找到关于如何返回的信息,如果它包含通配符匹配,而不是通配符匹配表示的字符串。
例如,
var myString = "abcde werrty qweert";
var newStr = MyMatchFunction("a*e", myString);
//myString = "abcde"
如何创建MyMatchFunction
?我在stackoverflow上进行了搜索,但是如果字符串包含通配符字符串,而不是它所表示的字符串,则所有与c#和通配符有关的操作都只是返回布尔值。
发布于 2018-06-06 03:30:50
您是否考虑过使用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
发布于 2018-06-06 04:14:04
对于模式为"a*b"
的"abcde werrty qweert"
,默认的通配符搜索将返回"abcde werrty qwee"
,但您可以使用gready搜索"abcde"
的结果。
使用Regex
进行WildCard
匹配的函数
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;
}
结果:
var myString = "abcde werrty qweert";
var newStr = WildCardMatch("a*e", myString);
//newStr = "abcde werrty qwee"
newStr = WildCardMatch("a*e", myString, Greedy: true);
//newStr = "abcde"
https://stackoverflow.com/questions/50707583
复制相似问题