1

I have a long string as below. I would like to replace some character when it found some keyword (.abc_ or .ABC_). As the system read line by line, if the keyword is found, then it will replace the word infront to become "john"

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

Changed to

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

Below is my code.

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

I am not able to get the word material or job in front of the keyword.

1
  • Check Index of substring and Try to compare words in UPPER Case or Lower case. Commented Sep 13, 2012 at 7:08

3 Answers 3

3
content =  Regex.Replace(content, @"\s\w+\.(abc|ABC)_", " john.$1_");
Sign up to request clarification or add additional context in comments.

3 Comments

can you make that into 1 line?
yes, don't know what I didn't think of it actually. I have edited accordingly.
+1. nice write-only solution :). Note: I suspect $1 should not be in replace string as it feels like .ABC_ should be removed from the output...
1

Use String.Format instead of this:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.