Can I use variables in a template in Regex (C #)

I have HTML text where I need to replace words with links to them. For example, I have text with the word "PHP" and want to replace it with <a href = "glossary.html # php"> PHP </a>. And there are many words that I need to replace.

My code is:

public struct GlossaryReplace
{
    public string word; // here the words, e.g. PHP
    public string link; // here the links to replace, e.g. glossary.html#php
}
public static GlossaryReplace[] Replaces = null;    

IHTMLDocument2 html_doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
string html_content = html_doc.body.outerHTML;

for (int i = 0; i < Replaces.Length; i++)
{
    String substitution = "<a class=\"glossary\" href=\"" + Replaces[i].link + "\">" + Replaces[i].word + "</a>";
    html_content = Regex.Replace(html_content, @"\b" + Replaces[i].word + "\b", substitution);
}
html_doc.body.innerHTML = html_content;

Problem - this does not work :( But,

html_content = Regex.Replace(html_content, @"\bPHP\b", "some replacement");

this code works well! I can not understand my mistake!

+3
source share
2 answers

You forgot @here:

@"\b" + Replaces[i].word + "\b"

Must be:

@"\b" + Replaces[i].word + @"\b"

I would also recommend using an HTML parser if you are modifying HTML. HTML Agility Pack is a useful library for this purpose.

+3
source

@ , , , .

:

html_content = Regex.Replace(html_content, @"\b" + Replaces[i].word + "\b", substitution);

html_content = Regex.Replace(html_content, @"\b" + Replaces[i].word + @"\b", substitution);

\b , (ASCII 8). , escape-, (, \s), , , .

; , , - Regex.Escape. , , @"\b" + Regex.Escape(Replaces[i].word) + @"\b" , , .

+3
source

Source: https://habr.com/ru/post/1773089/


All Articles