1

I am having following set of image map tags;

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
  <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

I need to extract href attribute and replace it with another url

I am using following code but does not seems to work;

string input = @"<area shape=""rect"" href=""http://www.google.com"">";
            string pattern = "(href=([^ ]+))";
Regex rgx = new Regex(pattern);
string result2 = rgx.Replace(input, m => m.Groups[1].Value.Replace(result,"test.com"));

Could someone please help me.

Thanks

user778930
  • 87
  • 4
  • 10
  • 1
    Please delineate exactly what you mean by "it doesn't work", it will be helpful to those answering the question. – jonsca Oct 09 '12 at 03:17
  • 1
    [You should not use regular expressions to parse HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Guillaume Oct 09 '12 at 03:18

2 Answers2

0

I can see two things that may be causing an issue. The first is, your regex is checking for a string in the format of href=http://example.com. Note, there are no quotes around the URL. So, we'll need to update the regex to handle the double-quotes like your input contains.

The second is that you're using the matched group 1, but your regex is actually matching two separate groups (and you want to replace the second one). You don't need the first matching group at all, so we can actually drop this part.

In all, try updating your regex to:

href="([^"]+)"

In your variable, it will look like:

string pattern = @"href=""([^""]+)""";
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
0

Have a look in this example:

StreamReader reader = new StreamReader("D:\\stack.html");
string testString = reader.ReadToEnd();

string replacedString = Regex.Replace(testString, @"(?<=href=).+?(?=\s)", "\"test.com\"");

StreamWriter writer = new StreamWriter("D:\\stack1.html");
writer.WriteLine(replacedString);

writer.Close();
reader.Close();

Hope you got it.

jomsk1e
  • 3,585
  • 7
  • 34
  • 59