簡體   English   中英

正則表達式結合了多種功能

[英]Regex combine more than 1 function

如何在我的代碼中為一個字符串調用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);
  }

現在,我要檢查“Téèááést”一詞,此后它應該看起來像Teaest。

你有嘗試過嗎?

string str = "Téèááést";
str = ecleaner(str);
str = acleaner(str);

您可以使用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 "";
}

或者:

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();

您還可以將擴展方法類與@pswg的答案結合使用,以使事情更加整潔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM