c#string替换关键字

时间:2012-09-13 07:02:39

标签: c# regex

我有一个长字符串如下。当我找到一些关键字(.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();
    }
}

我无法在关键字前面找到材料或工作。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

使用String.Format而不是:

var stringBuffer = new StringBuffer();
...
line = "insert into {0}.ABC_Inventory; Show select ..."
stringBuffer.AppendFormat(line, arg1, arg2, arg3);
...

答案 2 :(得分:1)

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