代码之家  ›  专栏  ›  技术社区  ›  Simon

如何一次性执行多个字符串替换?

  •  2
  • Simon  · 技术社区  · 16 年前

    我正在用C语言编写一个应用程序,它允许用户根据文件名执行数据库查询。

    我在用电话 Regex.Replace(string, MatchEvaluator) 重载以执行替换,因为我希望用户能够具有如下替换字符串 SELECT * FROM table WHERE record_id = trim($1) 即使我们使用的数据库不支持trim()之类的函数。

    我不想做一系列的替换,如果$1的值包含“$2”,那么两个替换都会发生。如何一次性执行多个字符串替换?我知道PHP的str_replace支持数组作为参数;C#有类似的函数吗?

    3 回复  |  直到 16 年前
        1
  •  3
  •   LukeH    16 年前

    没有内置功能,但您可以尝试以下功能:

    string foo = "the fish is swimming in the dish";
    
    string bar = foo.ReplaceAll(
        new[] { "fish", "is", "swimming", "in", "dish" },
        new[] { "dog", "lies", "sleeping", "on", "log" });
    
    Console.WriteLine(bar);    // the dog lies sleeping on the log
    
    // ...
    
    public static class StringExtensions
    {
        public static string ReplaceAll(
            this string source, string[] oldValues, string[] newValues)
        {
            // error checking etc removed for brevity
    
            string pattern =
                string.Join("|", oldValues.Select(Regex.Escape).ToArray());
    
            return Regex.Replace(source, pattern, m =>
                {
                    int index = Array.IndexOf(oldValues, m.Value);
                    return newValues[index];
                });
        }
    }
    
        2
  •  1
  •   Xander    16 年前

    最好的方法是循环遍历字符串数组,并在每次迭代过程中调用Replace,一般来说,这是其他函数在后台所做的。

    更好的方法是创建自己的方法来实现这一点,类似于PHP的str_replace的工作方式。

    请参见下面的示例,或者您可以根据您的具体需求进行更改

    // newValue - Could be an array, or even Dictionary<string, string> for both strToReplace/newValue
    private static string MyStrReplace(string strToCheck, string[] strToReplace, string newValue)
    {
        foreach (string s in strToReplace)
        {
            strToCheck = strToCheck.Replace(s, newValue);
        }
            return strToCheck;
    }
    
        3
  •  1
  •   Mark Evaul    14 年前

    我认为在模式和替换数组上循环是最好的选择。即使stru_replace也有您描述的问题。

    echo str_replace(array("a", "b", "c"), array("b", "c", "d"), "abc");
    
    result: "ddd"