如何在C#中的两个字符之间替换文本 [英] How to replace the text between two characters in c#

查看:448
本文介绍了如何在C#中的两个字符之间替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在两个定界符 {} 之间查找文本的正则表达式,我很困惑,然后用c#中的另一个文本替换该文本,如何替换?

I am bit confused writing the regex for finding the Text between the two delimiters { } and replace the text with another text in c#,how to replace?

我尝试过这个。

        StreamReader sr = new StreamReader(@"C:abc.txt");
        string line;
        line = sr.ReadLine();

        while (line != null)
        {

            if (line.StartsWith("<"))
            {
                if (line.IndexOf('{') == 29)
                {
                    string s = line;
                    int start = s.IndexOf("{");
                    int end = s.IndexOf("}");
                    string result = s.Substring(start+1, end - start - 1);

                }
            }
            //write the lie to console window
            Console.Write Line(line);
            //Read the next line
            line = sr.ReadLine();
        }
        //close the file
        sr.Close();
        Console.ReadLine();

我想用另一个文本替换找到的文本(结果)。

I want replace the found text(result) with another text.

推荐答案

string s = "data{value here} data";
int start = s.IndexOf("{");
int end = s.IndexOf("}", start);
string result = s.Substring(start+1, end - start - 1);
s = s.Replace(result, "your replacement value");

这篇关于如何在C#中的两个字符之间替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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