如何实现“查找、替换、下一步"在 C# 上的字符串中? [英] How to implement "Find, Replace, Next" in a String on C#?

查看:33
本文介绍了如何实现“查找、替换、下一步"在 C# 上的字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找这种情况的解决方案:

I'm searching for a solution to this case:

我在 DLL 中有一个方法,它接收一个字符串,其中包含一些作为占位符/参数"的词,这些词将被另一个特定方法的结果替换(也在 dll 内)

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)

过于简单:它是作为参数接收的查询字符串,用于 DLL 内的方法,其中匹配特定情况的 X 字将被替换.

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:

(在 .exe 应用程序上)

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

MyDLLClass.MyMethod(str);

所以,问题是:如果我替换这个字符串上的#GEN_COMPLEX_ID#,希望每个匹配上都应该有一个不同的,这不会发生,因为被替换的函数是一次性执行的(不是一步一步).所以,我想帮助实现这一点:逐步替换任何文本(例如查找某个单词,替换,比下一个...替换...下一个...等.

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.

你能帮我吗?谢谢!

推荐答案

这对我来说效果很好:

        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;
        }

这篇关于如何实现“查找、替换、下一步"在 C# 上的字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆