What I’m trying to do is open up a file and search for “searchText”. I want to replace all the instances of it in the file with a new link, which is actually just the filename with an achor link so instead of opening up javascript it just goes to another point in the page.
So far what I have is this:
private void writeNotes(){
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string content = reader.ReadToEnd();
reader.Close();
string fileName = openFileDialog1.SafeFileName;
string searchText = "<a class=\"x-fn\" href=\"javascript:void(0);\">";
string replaceText = "<a class=\"x-fn\" href=\"" + fileName + "#fn" + "\">";
content = Regex.Replace(content, searchText, replaceText);
StreamWriter writer = new StreamWriter(openFileDialog1.FileName);
writer.Write(content);
writer.Close();
However, after writing and closing… I open up the file and no changes were made. Besides that, what I want to do is add a number that counts up after “#fn” for every instance of replacement. So, basically, for every time I replace the javascript link with another, I want it to be:
<a class="x-fn" href="fileName#fn1">
And then when I replace the second instance of javascript, it reads
<a class="x-fn" href="fileName#fn2">
and so on…
I imagine I would have to count the instances of how many times the javascript appears, replace it, and use a for loop to iterate throughout all of the new links and add the #fn(n) at the end?
Your problem is that you have metacharacters (in this case, the open and close paren in “void(0)”). Instead of representing literal open and close parens, that is creating a regular expression group, which is causing your match to fail. If you escape the parens with a backslash, it will work as expected.
However, since you’re just matching a string literal, you don’t need to use regular expressions at all; it’ll be faster to use
string.Replace.As for the second part of your question, that’s a little trickier. There’s no easy way to do it that I know of, so the best approach is to look for your search text in the input, and then build up a
StringBuilderas you go along, incrementing a count variable. In the following example, the word “the” is replaced by “(0)” and “(1)” for simplicity’s sake, but you can adapt it to your problem easily enough.