return c#中基于通配符的字符串
return string based on wildcard in c#
我试图在 c# 中找到一个方法来 return 通配符匹配的字符串,但是我只能找到关于如何 return 如果它包含通配符匹配的信息,而不是通配符匹配代表的字符串。
例如,
var myString = "abcde werrty qweert";
var newStr = MyMatchFunction("a*e", myString);
//myString = "abcde"
我将如何创建 MyMatchFunction
?我在 Whosebug 上四处搜索,但与 c# 和通配符有关的所有内容都只是 returning 布尔值,判断字符串是否包含通配符字符串,而不是它所代表的字符串。
您是否考虑过使用正则表达式?
例如,使用模式 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
"abcde werrty qweert"
的 "a*b"
模式的通配符搜索默认将 returns "abcde werrty qwee"
,但您可以使用 gready 搜索 "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;
}
结果:
var myString = "abcde werrty qweert";
var newStr = WildCardMatch("a*e", myString);
//newStr = "abcde werrty qwee"
newStr = WildCardMatch("a*e", myString, Greedy: true);
//newStr = "abcde"
我试图在 c# 中找到一个方法来 return 通配符匹配的字符串,但是我只能找到关于如何 return 如果它包含通配符匹配的信息,而不是通配符匹配代表的字符串。
例如,
var myString = "abcde werrty qweert";
var newStr = MyMatchFunction("a*e", myString);
//myString = "abcde"
我将如何创建 MyMatchFunction
?我在 Whosebug 上四处搜索,但与 c# 和通配符有关的所有内容都只是 returning 布尔值,判断字符串是否包含通配符字符串,而不是它所代表的字符串。
您是否考虑过使用正则表达式?
例如,使用模式 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
"abcde werrty qweert"
的 "a*b"
模式的通配符搜索默认将 returns "abcde werrty qwee"
,但您可以使用 gready 搜索 "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;
}
结果:
var myString = "abcde werrty qweert";
var newStr = WildCardMatch("a*e", myString);
//newStr = "abcde werrty qwee"
newStr = WildCardMatch("a*e", myString, Greedy: true);
//newStr = "abcde"