How to implement “Find, Replace, Next” in a String on C#?

泄露秘密 提交于 2020-01-06 14:39:15

问题


I'm searching for a solution to this case:

I have a Method inside a DLL that receive a string that contains some words as "placeholders/parameters" that will be replaced by a result of another specific method (inside dll too)

Too simplificate: It's a query string received as an argument to be on a method inside a DLL, where X word that matchs a specifc case, will be replaced.

My method receive a string that could be like this:

(on .exe app)

string str = "INSERT INTO mydb.mytable (id_field, description, complex_number) VALUES ('#GEN_COMPLEX_ID#','A complex solution', '#GEN_COMPLEX_ID#');"

MyDLLClass.MyMethod(str);

So, the problem is: if i replace the #GEN_COMPLEX_ID# on this string, wanting that a different should be on each match, it not will happen because the replaced executes the function in a single shot (not step by step). So, i wanna help to implement this: a step by step replace of any text (like Find some word, replace, than next ... replace ... next... etc.

Could you help me? Thanks!


回答1:


This works pretty well for me:

        string yourOriginalString = "ab cd ab cd ab cd";
        string pattern = "ab";
        string yourNewDescription = "123";
        int startingPositionOffset = 0;
        int yourOriginalStringLength = yourOriginalString.Length;

        MatchCollection match = Regex.Matches(yourOriginalString, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

        foreach (Match m in match)
        {
            yourOriginalString = yourOriginalString.Substring(0, m.Index+startingPositionOffset) + yourNewDescription + yourOriginalString.Substring(m.Index + startingPositionOffset+ m.Length);
            startingPositionOffset = yourOriginalString.Length - yourOriginalStringLength;
        }



回答2:


If what you're asking is how to replace each placeholder with a different value, you can do it using the Regex.Replace overload which accepts a MatchEvaluator delegate, and executes it for each match:

// conceptually, something like this (note that it's not checking if there are
// enough values in the replacementValues array)

static string ReplaceMultiple(
      string input, string placeholder, IEnumerable<string> replacementValues)
{
    var enumerator = replacementValues.GetEnumerator();
    return Regex.Replace(input, placeholder, 
        m => { enumerator.MoveNext(); return enumerator.Current; });
}

This is, of course, presuming that all placeholders look the same.




回答3:


Pseudo-code

var split = source.Split(placeholder); // create array of items without placeholders
var result = split[0]; // copy first item
for(int i = 1; i < result.Length; i++)
{
    bool replace = ... // ask user
    result += replace ? replacement : placeholder; // to put replacement or not to put
    result += split[i]; // copy next item
}



回答4:


you should use the split method like this

        string [] placeholder = {"#Placeholder#"} ;
        string[] request = cd.Split(placeholder, StringSplitOptions.RemoveEmptyEntries);
        StringBuilder requetBuilding = new StringBuilder();
        requetBuilding.Append(request[0]); 
        int index = 1; 
        requetBuilding.Append("Your place holder replacement");
        requetBuilding.Append(request[index]); 
        index++;  //next replacement 
                  // requetBuilding.Append("Your next place holder replacement");
                  // requetBuilding.Append(request[index]); 


来源:https://stackoverflow.com/questions/26933069/how-to-implement-find-replace-next-in-a-string-on-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!