gpt4 book ai didi

c# - 删除部分 Regex.Match 字符串

转载 作者:行者123 更新时间:2023-11-30 16:54:18 26 4
gpt4 key购买 nike

所以我在字符串中有一个 HTML 表格。大部分 HTML 来自 FrontPage,所以它的格式大多很糟糕。这是它的外观的快速示例。

<b>Table 1</b>
<table class='class1'>
<tr>
<td>
<p>Procedure Name</td>
<td>
<p>Procedure</td>
</tr>
</table>
<p><b>Table 2</b></p>
<table class='class2'>
<tr>
<td>
<p>Procedure Name</td>
<td>
<p>Procedure</td>
</tr>
</table>
<p> Some text is here</p>

据我了解,FrontPage 会自动添加一个 <p>在每个新细胞中。

我想删除那些 <p>标签表内,但保留在表外。到目前为止,我尝试了 2 种方法:

第一种方法

第一种方法是每 <p> 使用一个 RegEx tp 捕获在表中标记然后到 Regex.Replace()删除它们。但是我从来没有设法为此获得正确的正则表达式。 (我知道用 RegEx 解析 HTML 不好。我认为数据很简单,可以对其应用 RegEx)。

我可以使用这个正则表达式很容易地得到每个表中的所有内容:<table.*?>(.*?)</table>

然后我只想抓取 <p>标签所以我写了这个:(?<=<table.*?>)(<p>)(?=</table>) .这不符合任何东西。 (显然 .NET 允许在其后视中使用量词。至少这是我在使用 http://regexhero.net/tester/ 时的印象)

有什么方法可以修改此 RegEx 以仅捕获我需要的内容?

第二种方法

第二种方法是只将表格内容捕获到一个字符串中,然后 String.Replace()删除 <p>标签。我正在使用以下代码来捕获匹配项:

MatchCollection tablematch = Regex.Matches(htmlSource, @"<table.*?>(.*?)</table>", RegexOptions.Singleline);

htmlSource是一个包含整个 HTML 页面的字符串,这个变量是处理后将发送回客户端的内容。我只想删除我需要从 htmlSource 中删除的内容.

如何使用 MatchCollection 删除 <p>标签,然后将更新后的表格发送回 htmlSource

谢谢

最佳答案

此答案基于第二种建议方法。更改正则表达式以匹配表内的所有内容:

<table.*?table>

并使用 Regex.Replace 指定 MatchEvaluator 来执行所需的替换:

Regex myRegex = new Regex(@"<table.*?table>", RegexOptions.Singleline);
string replaced = myRegex.Replace(htmlSource, m=> m.Value.Replace("<p>",""));
Console.WriteLine(replaced);

使用问题输入的输出:

<b>Table 1</b>
<table class='class1'>
<tr>
<td>
Procedure Name</td>
<td>
Procedure</td>
</tr>
</table>
<p><b>Table 2</b></p>
<table class='class2'>
<tr>
<td>
Procedure Name</td>
<td>
Procedure</td>
</tr>
</table>
<p> Some text is here</p>

关于c# - 删除部分 Regex.Match 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30713644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com