c#如何替换两个字符之间的文本 [英] How to replace the text between two characters in c#
本文介绍了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.
推荐答案
Use Regex with pattern: {([^}]+)}
Use Regex with pattern: {([^}]+)}
Regex yourRegex = new Regex(@"{([^}]+)}");
string result = yourRegex.Replace(yourString, "anyReplacement");
这篇关于c#如何替换两个字符之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文