c#字符串替换关键字



我有一个长字符串,如下所示。当它找到一些关键字(.abc_ or .ABC_)时,我想替换一些字符。当系统逐行读取时,如果找到关键字,则会将单词infront替换为"john"

insert into material.abc_Inventory; Delete * from table A; ....   
insert into job.ABC_Inventory; Show select .....; ....

已更改为

insert into john.ABC_Inventory; Delete * from table A;    
insert into john.ABC_Inventory; Show select .....;

下面是我的代码。

string output = string.Empty;
using (StringReader reader = new StringReader(content))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        if (line.Contains(".ABC_"))
            line.Replace(" word in front of the keyword" + line.Substring(line.IndexOf(".ABC_")), " john" + line.Substring(line.IndexOf(".ABC_")));
            output += whole line of edited code; 
        else if (line.Contains(".abc_"))
            line.Replace(" word in front of the keyword" + line.Substring(line.IndexOf(".abc_")), " john" + line.Substring(line.IndexOf(".abc_")));
            output += whole line of edited code; 
        else
            output += line.ToString();
    }
}

我无法获得关键字前面的单词material或job。

content =  Regex.Replace(content, @"sw+.(abc|ABC)_", " john.$1_");

使用String.Format而不是这个:

var stringBuffer = new StringBuffer();
...
line = "insert into {0}.ABC_Inventory; Show select ..."
stringBuffer.AppendFormat(line, arg1, arg2, arg3);
...
var list = line.Split(new[] {".abc_", ".ABC_"}, 
                              StringSplitOptions.RemoveEmptyEntries);
if (list.Count() > 1)
{
    string toReplace = list.First().Split(' ').Last();
    string output = line.Replace(toReplace, "john");
}

最新更新