【发布时间】:2016-04-08 19:39:42
【问题描述】:
编辑: 此示例使用 html,但我需要这种类型的场景来处理其他类型的字符串。请将此视为正则表达式问题,而不是 html 问题。
假设我有一个这样的字符串:
<h1>Hello</h1><h2>World</h2><h3>!</h3>
我可能需要将文本替换为 any 其中一个标题标签,但让我们使用这个示例,我只想将 <h2> 修改为如下所示:
<h1>Hello</h1><div id="h2div"></div><h2>World</h2><h3>!</h3>
由于我可能需要替换任何标题,我只使用正则表达式搜索<h*。现在,我想让我的代码说“在你找到的所有<h* 标签中,只替换第二个”。
我以为我在这里找到了答案: How do I replace a specific occurrence of a string in a string?
不幸的是,结果不是我想要的。这是我的示例代码:
private void button1_Click(object sender, EventArgs e)
{
//sample html file string:
var htmlText = "<h1>Hello</h1><h2>World</h2><h3>!</h3>";
//this text should replace <h2 with <div id="h2div"></div><h2"
var replacementString = "<div id=\"" + "h2div" + "\"" + "</div>" + "<h2";
int replacementIndex = 1; //only replace the second occurence found by regex.
//find ALL occurrences of <h1 through <h6 in the file, but only replace <h2.
htmlText = Regex.Replace(htmlText, "<h([1-6])", m => replacementString + replacementIndex++);
}
我指定replacementIndex 还是replacementIndex++ 都没有关系,这是有道理的,但我只是想将代码与我找到的答案尽可能地匹配。
输出如下所示:
<div id="h2div"></div><h21>Hello</h1><div id="h2div"></div><h22>World</h2><div id="h2div"></div><h23>!</h3>
这里有很多不应该发生的事情。首先,应该只创建一个<div> 标签,而不是三个。其次,<h 标签只被替换而不是<h2,所以现在我们最终得到<h21、<h22 和<h23。
从几个月前开始,我对正则表达式匹配的理解越来越好,但我对正则表达式匹配器和组真的不熟悉;我想这就是我在这里可能需要的。
您能否推荐我如何修复代码以便替换正则表达式匹配的特定索引?
【问题讨论】:
-
我建议使用 HtmlAgilityPack 而不是 Regex 来处理 HTML。
-
这只是一个例子。我有一些非 html 场景也需要这样做。