I am trying to replace words in a long string with some HTML-tags. I seem to miss something when trying to do this for multiple words from a List, it does however work nicely for single Words.
Here is what i tried: For testing purposes i reduced and altered the string to this:
string strTest = "Ein toller Testtext mit Folge und Folgen sowie Folgen<p> und <p>Folge und Cauchyfolgen und Cauchy-Folgen und Folgeerscheinungen und Folgendem";
The following code was used as a text to replace "Folge" with "WOW":
strResult = Regex.Replace(strTest, "\\b" + "Folge" + "\\b", "WOW");
This resulted in: "Ein toller Testtext mit WOW und Folgen sowie Folgen<p> und <p>WOW und Cauchyfolgen und Cauchy-Folgen und Folgeerscheinungen und Folgendem", which is the desired result for a single word.
The following code resulted in the same, but is using my list of Objects, where "strWort" is the word i want to replace. Note the Value of listTooltips[39].strWort is "Folge".
strResult = Regex.Replace(strTest, "\\b" + listTooltips[39].strWort + "\\b", "WOW");
In the next step i tried to do this for the whole list. So i did the following:
for (int i = 0; i < listTooltips.Count(); i++)
{
strResult = Regex.Replace(strTest, "\\b" + listTooltips[i].strWort + "\\b", "WOW");
}
The result is an unchanged String. And i am lost as to why. As noted it does work if i only put one Word to replace, even if i use a specific object from my list. So i am quite sure the code for the list is not wrong, at least not completly.
Additional things i tried:
- putting the value of each word into a seperate string and using that for the Regex.Replace. Failed.
- using a MessageBox.Show() to display the value of listTooltips[i].strWort to make sure, everything outputting as expected.
- using Regex.Match to check if the above code actually finds anything and yes, it does find everything. It just does not replace ist for some reason.
- not using Regex and going the string.replace-method instead. This is working with the above loop, but is causing differend unwanted results due to missing a filter / matchmode. i.e. "Folgen" is getting replaced to "WOWn" ect.
Really wondering WHY this is behaing as it does mainly, to better understand it. But id love a solution as well of corse :-)
Thanks in advance!