Take the 2-minute tour ×

So i have this html:

<img src="images" alt="alt" />
alt <a href ="http://google/something">alt</a>
test hallo world monkey

and a dictionary containing

{alt, test, hallo, world, monkey, something}

so i need a regex or another method to replace words that are not within a A tag or a img tag I have tryed the following regex:



share|improve this question
WHYT; What Have You Tried. –  OptimusCrime Jul 31 '12 at 9:45
@OptimusCrime See my edit –  Kimtho6 Jul 31 '12 at 9:46
Wouldn't this also replace the alt in your cool emoticon image too, since it has an 'alt' attribute? –  MetalFrog Sep 20 '12 at 12:16
Yes and thats the problem! –  Kimtho6 Sep 20 '12 at 12:26
add comment

2 Answers

up vote 1 down vote accepted

You could use regex and do a negative lookahead and lookbehind for letters:


in your example this would look like this:

bodyText = Regex.Replace(bodyText, "(?<![a-zA-Z])" + article.headword + "(?![a-zA-Z])", "<a class=\"dic\" href=\"#\">" + article.headword + "</a>");

My first intend was to do a positive search for whitespace characters, but then I thought of punctuation and stuff like this, a keyword is still a keyword if it has a .,!? at the end, right? So lookaheads and lookbehinds essentially check if something preceeding or succeeding your keyword, without replacing these, too.

share|improve this answer
Thanks for the help mate :) –  Kimtho6 Jul 31 '12 at 11:28
add comment

This is what i ended up doing

var regex = new Regex("(?<![a-zA-Z" + SpecialChars + "])" + article.headword + "(?![a-zA-Z" + SpecialChars + "])+(?!==)");

bodyText = regex.Replace(bodyText, "<a href=\"#dic\">" + headword + "</a>");

This will only replace the first one

share|improve this answer
add comment

Your Answer


