【问题标题】:How can I removed the rest of string after a particular string/pattern? [duplicate]如何在特定字符串/模式之后删除字符串的其余部分? [复制]
【发布时间】:2026-02-08 03:00:01
【问题描述】:

有谁知道如何在特定字符串或模式之后删除字符串的其余部分?

例如: 我将 html 代码保存为如下字符串:

字符串测试;

test = '<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title></head><body><table> <tr><td>test</td></tr> </table><div id="13"> </body> test test test test </html>'

如何在 C# .net 中删除 &lt;div id="13"&gt; 之后的其余文本?

【问题讨论】:

  • 那个“特殊符号”是什么?您知道它的位置还是要剪切的文本?
  • 语义有什么规则吗?我可以看到 &lt;div id="13"&gt; 没有结束标签。有什么特殊情况吗?
  • 不要使用正则表达式解析 HTML。

标签: c# .net


【解决方案1】:

如果你想排除结束标记,你可以使用这个:

string test = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"><title></title></head><body><table> <tr><td>test</td></tr> </table><div id=\"13\"> </body> test test test test </html>";
string result = test.Split(new string[] { "<div id=\"13\">"}, StringSplitOptions.None).FirstOrDefault();

如果你想包含结束标记,你可以使用这个:

string test = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"><title></title></head><body><table> <tr><td>test</td></tr> </table><div id=\"13\"> </body> test test test test </html>";
string endString = "<div id=\"13\">";
string result = test.Substring(0, test.IndexOf(endString) + endString.Length);

请注意,字符串文字必须用双引号字符而不是撇号括起来,并且其中的引号字符必须通过在它们前面加上 \ 来转义。

另外请注意,在我的代码中,我没有进行任何类型的验证,这取决于您。 :)

【讨论】:

  • 只有当它是一个字符串字面量(在result 中的拆分标记的情况下)时,它们才能被转义。 test 中显示的 html 很可能是从 Internet 下载或从文件中读取的,在这种情况下不需要修改。
  • 最后,任何以@ 为前缀的字符串都不需要转义序列
  • 双引号仍然需要它们(否则编译器怎么知道字符串是否已经结束?),但在这种情况下,您必须使用双双引号。 :D
【解决方案2】:

有很多方法可以实现这一点/使用哪种方法取决于您的确切要求(即您是在搜索&lt;div id="13"&gt; 还是您想要任何带有数字 id 的 div 标签/您是否关心它是否具有其他属性/您是否关心文本中的额外空格/您是否真的使用字符串或正在解析 html;等等。

以下是如何使用正则表达式匹配确切字符串的示例。这种方法的一个优点是它为您提供了很大的灵活性,因此随着您的需求得到更好的定义,应该很容易调整。

    var regex = new Regex(".*?<div id=\"13\">");
    var test = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"><title></title></head><body><table> <tr><td>test</td></tr> </table><div id=\"13\"> </body> test test test test </html>";
    var match = regex.Match(test);
    if (match.Success)
    {
        Console.WriteLine("Found!");
        Console.WriteLine(match.Value);
    }

完整代码:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var regex = new Regex(".*?<div id=\"13\">");
        var test = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head runat=\"server\"><title></title></head><body><table> <tr><td>test</td></tr> </table><div id=\"13\"> </body> test test test test </html>";
        var match = regex.Match(test);
        if (match.Success)
        {
            Console.WriteLine("Found!");
            Console.WriteLine(match.Value);
        }
        else
        {
            Console.WriteLine("Not Found!");
        }
        Console.ReadLine();         
    }
}

【讨论】: