[英]Regex combine more than 1 function
How can I call 2 functions in my code for one string? 如何在我的代码中为一个字符串调用2个函数?
public static string ecleaner(string str)
{
return Regex.Replace(str, "[éèê]+", "e", RegexOptions.Compiled);
}
public static string acleaner(string str)
{
return Regex.Replace(str, "[áàâ]+", "a", RegexOptions.Compiled);
}
Now I want to check the word "Téèááést" ,after this it should look like Teaest . 现在,我要检查“Téèááést”一词,此后它应该看起来像Teaest。
Did you try this? 你有尝试过吗?
string str = "Téèááést";
str = ecleaner(str);
str = acleaner(str);
You could use a MatchEvaluator
delegate, like this: 您可以使用
MatchEvaluator
委托,如下所示:
public static string cleaner(string str)
{
return Regex.Replace(str, "(?<a>[áàâ]+)|(?<e>[éèê]+)", onMatch, RegexOptions.Compiled);
}
private static string onMatch(Match m)
{
if (m.Groups["a"].Success)
return "a";
if (m.Groups["e"].Success)
return "e";
return "";
}
Or alternatively: 或者:
public static string cleaner(string str)
{
var groups = new[] { "a", "e" };
return Regex.Replace(str, "(?<a>[áàâ]+)|(?<e>[éèê]+)", m => groups.First(g => m.Groups[g].Success), RegexOptions.Compiled);
}
public static class StringExtensions
{
public static string ecleaner(this string str)
{
return Regex.Replace(str, "[éèê]+", "e", RegexOptions.Compiled);
}
public static string acleaner(this string str)
{
return Regex.Replace(str, "[áàâ]+", "a", RegexOptions.Compiled);
}
}
//...
var result = "Téèááést".ecleaner().acleaner();
You could also combine an extension method class with @pswg's answer, to make things even neater. 您还可以将扩展方法类与@pswg的答案结合使用,以使事情更加整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.