tags:

views:

669

answers:

3

Hello I have the following code

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            string searchText = "find this text, and some other text";
            string replaceText = "replace with this text";


            String query = "%SystemDrive%";
            string str = Environment.ExpandEnvironmentVariables(query);
            string filePath = (str + "mytestfile.xml"); 

            StreamReader reader = new StreamReader( filePath );
            string content = reader.ReadToEnd();
            reader.Close();

            content = Regex.Replace( content, searchText, replaceText );

            StreamWriter writer = new StreamWriter( filePath );
            writer.Write( content );
            writer.Close();
        }
    }
}

the replace doesn't find the search text because it is on separate lines like

find this text,
and some other text.

How would I write the regex epression so that it will find the text.

+1  A: 

Why are you trying to use regular expressions for a simple search and replace? Just use:

content.Replace(searchText,replaceText);

You may also need to add '\n' into your string to add a line break in order for the replace to match.

Try changing search text to:

string searchText = "find this text,\n" + 
                    "and some other text";
Stephan
I tried executing this way but I still can't seem to replace the text if I do a replace for a single line it works
Adonis L
You need to add a line break in your search text. Try entering the search text verbatim. I'll edit my answer to show you.
Stephan
+4  A: 

To search for any whitespace (spaces, line breaks, tabs, ...), you should use \s in your regular expression:

string searchText = @"find\s+this\s+text,\s+and\s+some\s+other\s+text";

Of course, this is a very limited example, but you get the idea...

Philippe Leybaert
A: 

This is a side note for your specific question, but you are re-inventing some functionality that the framework provides for you. Try this code:

static void Main(string[] args)
{
    string searchText = "find this text, and some other text";
    string replaceText = "replace with this text";

    string root = Path.GetPathRoot(Environment.SystemDirectory);
    string filePath = (root + "mytestfile.xml"); 

    string content = File.ReadAllText(filePath);
    content = content.Replace(searchText, replaceText);

    File.WriteAllText(filePath, content);  
}
Joel Coehoorn
Thanks I modified my code using this functionality
Adonis L