【问题标题】:Can I use variables in pattern in Regex (C#)我可以在正则表达式(C#)中使用模式中的变量吗
【发布时间】:2010-11-05 01:48:53
【问题描述】:

我有一些 HTML 文本,我需要将单词替换为它们上的链接。例如,我有一个带有单词“PHP”的文本,并且想用 PHP 替换它。还有很多词需要替换。

我的代码:

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;

问题是 - 这不起作用:(但是,

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

这段代码运行良好!我无法理解我的错误!

【问题讨论】:

  • 您永远不会为“替换”分配任何内容,因此您的 for 循环将永远不会做任何事情。

标签: c# regex


【解决方案1】:

你在这里忘记了@

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

应该是:

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

如果您正在修改 HTML,我还建议您使用 HTML 解析器。 HTML Agility Pack 是一个有用的库。

【讨论】:

    【解决方案2】:

    字符串的@前缀仅适用于紧随其后的字符串,因此当您连接字符串时,您可能必须在每个字符串上使用它。

    改变这个:

    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)。如果您使用字符串中不存在的转义码(例如\s),则会出现编译器错误,但在这种情况下不会出现,因为该代码同时存在于字符串和正则表达式中。

    附带说明;在动态创建正则表达式模式时有用的方法是Regex.Escape 方法。它将字符串中的字符转义以在模式中使用,因此@"\b" + Regex.Escape(Replaces[i].word) + @"\b" 将使模式工作,即使单词包含在正则表达式中具有特殊含义的字符。

    【讨论】:

    • 我知道在正则表达式中使用 \b。也感谢您提供有关 Regex.Escape 的信息
    猜你喜欢
    • 2010-09-29
    • 2012-01-24
    • 2021-10-20
    • 2013-05-23
    • 2021-05-19
    • 1970-01-01
    • 2011-02-06
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多