You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET (C#) 如何移除字符串中的首尾标签

实现方案

实现逻辑

  • 定位字符串中第一个<和紧随其后的第一个>,确定首个完整HTML标签的结束位置
  • 定位字符串中最后一个>和其前方的最后一个<,确定末尾完整HTML标签的开始位置
  • 截取两个位置中间的内容作为返回结果,边界异常场景直接返回原字符串避免报错

注:该方案适用于标准无内嵌特殊字符的HTML标签场景,如果需要处理属性内嵌</>、不规范闭合的复杂HTML,建议引入专业HTML解析库处理。

完整C#代码

using System;

public static class HtmlStringProcessor
{
    public static string TrimFirstAndLastHtmlTag(string input)
    {
        // 空值或空白字符串直接返回
        if (string.IsNullOrWhiteSpace(input))
            return input;
        
        // 定位第一个开始标签的起止边界
        int firstOpenTagIndex = input.IndexOf('<');
        if (firstOpenTagIndex == -1)
            return input;
        
        int firstCloseTagIndex = input.IndexOf('>', firstOpenTagIndex + 1);
        if (firstCloseTagIndex == -1)
            return input;
        
        // 定位最后一个结束标签的起止边界
        int lastCloseTagIndex = input.LastIndexOf('>');
        if (lastCloseTagIndex == -1)
            return input;
        
        int lastOpenTagIndex = input.LastIndexOf('<', lastCloseTagIndex - 1);
        if (lastOpenTagIndex == -1 || lastOpenTagIndex <= firstCloseTagIndex)
            return string.Empty;
        
        // 截取首尾标签之间的内容
        int startIndex = firstCloseTagIndex + 1;
        int contentLength = lastOpenTagIndex - startIndex;
        return input.Substring(startIndex, contentLength);
    }
}

测试示例

// 测试用例1
string input1 = "<p>here is some text</p>";
Console.WriteLine(HtmlStringProcessor.TrimFirstAndLastHtmlTag(input1));
// 输出:here is some text

// 测试用例2
string input2 = "<h3>here is some header</h3>";
Console.WriteLine(HtmlStringProcessor.TrimFirstAndLastHtmlTag(input2));
// 输出:here is some header

// 测试用例3
string input3 = "<ul><li>fsdfsdfsd</li></ul><p>some p text</p>";
Console.WriteLine(HtmlStringProcessor.TrimFirstAndLastHtmlTag(input3));
// 输出:<li>fsdfsdfsd</li></ul><p>some p text

内容的提问来源于stack exchange,提问作者E.D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:15:10