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

正则表达式需求:检测字符串未闭合标签与嵌套标签

检测未闭合及嵌套的<:...:>标签(HTML转义版)

Got it, let's work through this problem together. You're dealing with HTML-escaped tags like &lt;:Id:&gt; (which translates to <:Id:>) and need to detect two specific issues: unclosed tags and nested tags. Here's how to approach both:

1. 检测嵌套标签

Nested tags happen when a &lt;: start tag appears inside another unclosed &lt;: ... :&gt; block (like your test case &lt;:&lt;:Id:&gt;). To spot this, use a regex that matches any &lt;: followed by another &lt;: before the corresponding :&gt;:

&lt;:.*?&lt;:

C# Code Example

string testString = @"C:\Dic\&lt;:&lt;:Id:&gt;.&lt;:Dic:&gt;testtest&lt;:Location:&gt;.Test.doc";
string nestedTagPattern = @"&lt;:.*?&lt;:>"; // 实际代码中使用@符号时写为 @"&lt;:.*?&lt;:"

bool hasNestedTags = Regex.IsMatch(testString, nestedTagPattern);
if (hasNestedTags)
{
    Console.WriteLine("⚠️ 检测到嵌套标签");
}

2. 检测未闭合标签

Unclosed tags come in two flavors:

  • A &lt;: start tag with no matching :&gt; end tag
  • A :&gt; end tag with no preceding &lt;: start tag

检测未闭合的起始标签

Use this regex to match any &lt;: that isn't followed by a :&gt; before the end of the string:

&lt;:(?:(?!:&gt;).)*$

检测未闭合的结束标签

This regex matches :&gt; that either appears before any &lt;:, or comes after a properly closed tag (indicating an extra end tag):

^(?:(?!&lt;:).)*:&gt;|&lt;:.*?:&gt;.*?:&gt;

C# Code Example for Unclosed Tags

string unclosedStartPattern = @"&lt;:(?:(?!:&gt;).)*$";
string unclosedEndPattern = @"^(?:(?!&lt;:).)*:&gt;|&lt;:.*?:&gt;.*?:&gt;";

bool hasUnclosedStart = Regex.IsMatch(testString, unclosedStartPattern);
bool hasUnclosedEnd = Regex.IsMatch(testString, unclosedEndPattern);

if (hasUnclosedStart || hasUnclosedEnd)
{
    Console.WriteLine("⚠️ 检测到未闭合标签");
}

3. 一次性验证标签合法性(无嵌套+全闭合)

If you want a single check to confirm the string has no nested or unclosed tags, use this .NET-specific regex (leveraging atomic groups to avoid excessive backtracking):

^[^&lt;:]*+(?:&lt;:([^&lt;:&gt;]+):&gt;[^&lt;:]*+)*+$

C# Code Example

string validTagPattern = @"^[^&lt;:]*+(?:&lt;:([^&lt;:&gt;]+):&gt;[^&lt;:]*+)*+$";
bool isTagStructureValid = Regex.IsMatch(testString, validTagPattern);

if (!isTagStructureValid)
{
    Console.WriteLine("⚠️ 字符串存在嵌套标签或未闭合标签");
}

Testing Your Sample Strings

  • For your first test string (C:\\Dic\\&lt;:&lt;:Id:&gt;.&lt;:Dic:&gt;testtest&lt;:Location:&gt;.Test.doc): The regex will detect nested tags.
  • For your second test string (&lt;:C:\\Dic\\&lt;:Id:&gt;.&lt;:Dic:&gt;testtest&lt;:Location:&gt;.Test.doc:&gt;): The regex will detect nested tags (the outer tag wraps inner valid tags).

内容的提问来源于stack exchange,提问作者dMilan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:49:24