正则表达式需求:检测字符串未闭合标签与嵌套标签
<:...:>标签(HTML转义版) Got it, let's work through this problem together. You're dealing with HTML-escaped tags like <:Id:> (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 <: start tag appears inside another unclosed <: ... :> block (like your test case <:<:Id:>). To spot this, use a regex that matches any <: followed by another <: before the corresponding :>:
<:.*?<:
C# Code Example
string testString = @"C:\Dic\<:<:Id:>.<:Dic:>testtest<:Location:>.Test.doc"; string nestedTagPattern = @"<:.*?<:>"; // 实际代码中使用@符号时写为 @"<:.*?<:" bool hasNestedTags = Regex.IsMatch(testString, nestedTagPattern); if (hasNestedTags) { Console.WriteLine("⚠️ 检测到嵌套标签"); }
2. 检测未闭合标签
Unclosed tags come in two flavors:
- A
<:start tag with no matching:>end tag - A
:>end tag with no preceding<:start tag
检测未闭合的起始标签
Use this regex to match any <: that isn't followed by a :> before the end of the string:
<:(?:(?!:>).)*$
检测未闭合的结束标签
This regex matches :> that either appears before any <:, or comes after a properly closed tag (indicating an extra end tag):
^(?:(?!<:).)*:>|<:.*?:>.*?:>
C# Code Example for Unclosed Tags
string unclosedStartPattern = @"<:(?:(?!:>).)*$"; string unclosedEndPattern = @"^(?:(?!<:).)*:>|<:.*?:>.*?:>"; 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):
^[^<:]*+(?:<:([^<:>]+):>[^<:]*+)*+$
C# Code Example
string validTagPattern = @"^[^<:]*+(?:<:([^<:>]+):>[^<:]*+)*+$"; bool isTagStructureValid = Regex.IsMatch(testString, validTagPattern); if (!isTagStructureValid) { Console.WriteLine("⚠️ 字符串存在嵌套标签或未闭合标签"); }
Testing Your Sample Strings
- For your first test string (
C:\\Dic\\<:<:Id:>.<:Dic:>testtest<:Location:>.Test.doc): The regex will detect nested tags. - For your second test string (
<:C:\\Dic\\<:Id:>.<:Dic:>testtest<:Location:>.Test.doc:>): The regex will detect nested tags (the outer tag wraps inner valid tags).
内容的提问来源于stack exchange,提问作者dMilan

