正则表达式无法处理流氓方括号

时间:2011-10-27 20:59:46

标签: c# .net regex c#-4.0 recursion

感谢过去的聪明才智,我有这个惊人的递归正则表达式,可以帮助我在一个文本块中转换自定义BBCode样式的标签。

/// <summary>
/// Static class containing common regular expression strings.
/// </summary>
public static class RegularExpressions
{
    /// <summary>
    /// Expression to find all root-level BBCode tags. Use this expression recursively to obtain nested tags.
    /// </summary>
    public static string BBCodeTags
    {
        get
        {
            return @"
                    (?>
                      \[ (?<tag>[^][/=\s]+) \s*
                      (?: = \s* (?<val>[^][]*) \s*)?
                      ]
                    )

                    (?<content>
                      (?>
                        \[(?<innertag>[^][/=\s]+)[^][]*]
                        |
                        \[/(?<-innertag>\k<innertag>)]
                        |
                        [^][]+
                      )*
                      (?(innertag)(?!))
                    )

                    \[/\k<tag>]
                    ";
        }
    }
}

这个正则表达式运行得很漂亮,在所有标签上递归匹配。像这样:

[code]  
    some code  
    [b]some text [url=http://www.google.com]some link[/url][/b]  
[/code]

正则表达式完全符合我的要求并匹配[code]标记。它将其分为三组:标记,可选值和内容。标记是标记名称(在本例中为“代码”)。可选值是等于(=)符号后面的值(如果有)。内容是开始和结束标记之间的所有内容。

可以递归使用正则表达式来匹配嵌套标记。因此,在[code]上匹配后,我会再次针对内容组运行它,它将匹配[b]标记。如果我在下一个内容组中再次运行它,那么它将匹配[url]标记。

所有这一切都美妙而美味,但它在一个问题上打嗝。它无法处理流氓方括号。

[code]This is a successful match.[/code]

[code]This is an [ unsuccessful match.[/code]

[code]This is also an [unsuccessful] match.[/code]

我真的很喜欢正则表达式,但是如果有人知道如何调整这个正则表达式来正确地忽略流氓括号(括号不构成开始标记和/或没有匹配的结束标记)以便它仍然匹配周围的标签,我会非常感激:D

提前致谢!

修改

如果您有兴趣查看我使用此表达式you are welcome to的方法。

3 个答案:

答案 0 :(得分:3)

我做了一个程序,可以以可调试的,开发人员友好的方式解析你的字符串。它不像那些正则表达式的小代码,但它有一个积极的一面:你可以调试它,并根据需要进行微调。

实现是descent recursive parser,但如果您需要某种上下文数据,则可以将其全部放在ParseContext类中。

这很长,但我认为它比基于正则表达式的解决方案更好。

要测试它,请创建一个控制台应用程序,并使用以下代码替换Program.cs中的所有代码:

using System.Collections.Generic;
namespace q7922337
{
    static class Program
    {
        static void Main(string[] args)
        {
            var result1 = Match.ParseList<TagsGroup>("[code]This is a successful match.[/code]");
            var result2 = Match.ParseList<TagsGroup>("[code]This is an [ unsuccessful match.[/code]");
            var result3 = Match.ParseList<TagsGroup>("[code]This is also an [unsuccessful] match.[/code]");
            var result4 = Match.ParseList<TagsGroup>(@"
                        [code]  
                            some code  
                            [b]some text [url=http://www.google.com]some link[/url][/b]  
                        [/code]");
        }
        class ParseContext
        {
            public string Source { get; set; }
            public int Position { get; set; }
        }
        abstract class Match
        {
            public override string ToString()
            {
                return this.Text;
            }
            public string Source { get; set; }
            public int Start { get; set; }
            public int Length { get; set; }
            public string Text { get { return this.Source.Substring(this.Start, this.Length); } }
            protected abstract bool ParseInternal(ParseContext context);
            public bool Parse(ParseContext context)
            {
                var result = this.ParseInternal(context);
                this.Length = context.Position - this.Start;
                return result;
            }
            public bool MarkBeginAndParse(ParseContext context)
            {
                this.Start = context.Position;
                var result = this.ParseInternal(context);
                this.Length = context.Position - this.Start;
                return result;
            }
            public static List<T> ParseList<T>(string source)
                where T : Match, new()
            {
                var context = new ParseContext
                {
                    Position = 0,
                    Source = source
                };
                var result = new List<T>();
                while (true)
                {
                    var item = new T { Source = source, Start = context.Position };
                    if (!item.Parse(context))
                        break;
                    result.Add(item);
                }
                return result;
            }
            public static T ParseSingle<T>(string source)
                where T : Match, new()
            {
                var context = new ParseContext
                {
                    Position = 0,
                    Source = source
                };
                var result = new T { Source = source, Start = context.Position };
                if (result.Parse(context))
                    return result;
                return null;
            }
            protected List<T> ReadList<T>(ParseContext context)
                where T : Match, new()
            {
                var result = new List<T>();
                while (true)
                {
                    var item = new T { Source = this.Source, Start = context.Position };
                    if (!item.Parse(context))
                        break;
                    result.Add(item);
                }
                return result;
            }
            protected T ReadSingle<T>(ParseContext context)
                where T : Match, new()
            {
                var result = new T { Source = this.Source, Start = context.Position };
                if (result.Parse(context))
                    return result;
                return null;
            }
            protected int ReadSpaces(ParseContext context)
            {
                int startPos = context.Position;
                int cnt = 0;
                while (true)
                {
                    if (startPos + cnt >= context.Source.Length)
                        break;
                    if (!char.IsWhiteSpace(context.Source[context.Position + cnt]))
                        break;
                    cnt++;
                }
                context.Position = startPos + cnt;
                return cnt;
            }
            protected bool ReadChar(ParseContext context, char p)
            {
                int startPos = context.Position;
                if (startPos >= context.Source.Length)
                    return false;
                if (context.Source[startPos] == p)
                {
                    context.Position = startPos + 1;
                    return true;
                }
                return false;
            }
        }
        class Tag : Match
        {
            protected override bool ParseInternal(ParseContext context)
            {
                int startPos = context.Position;
                if (!this.ReadChar(context, '['))
                    return false;
                this.ReadSpaces(context);
                if (this.ReadChar(context, '/'))
                    this.IsEndTag = true;
                this.ReadSpaces(context);
                var validName = this.ReadValidName(context);
                if (validName != null)
                    this.Name = validName;
                this.ReadSpaces(context);
                if (this.ReadChar(context, ']'))
                    return true;
                context.Position = startPos;
                return false;
            }
            protected string ReadValidName(ParseContext context)
            {
                int startPos = context.Position;
                int endPos = startPos;
                while (char.IsLetter(context.Source[endPos]))
                    endPos++;
                if (endPos == startPos) return null;
                context.Position = endPos;
                return context.Source.Substring(startPos, endPos - startPos);
            }
            public bool IsEndTag { get; set; }
            public string Name { get; set; }
        }
        class TagsGroup : Match
        {
            public TagsGroup()
            {
            }
            protected TagsGroup(Tag openTag)
            {
                this.Start = openTag.Start;
                this.Source = openTag.Source;
                this.OpenTag = openTag;
            }
            protected override bool ParseInternal(ParseContext context)
            {
                var startPos = context.Position;
                if (this.OpenTag == null)
                {
                    this.ReadSpaces(context);
                    this.OpenTag = this.ReadSingle<Tag>(context);
                }
                if (this.OpenTag != null)
                {
                    int textStart = context.Position;
                    int textLength = 0;
                    while (true)
                    {
                        Tag tag = new Tag { Source = this.Source, Start = context.Position };
                        while (!tag.MarkBeginAndParse(context))
                        {
                            if (context.Position >= context.Source.Length)
                            {
                                context.Position = startPos;
                                return false;
                            }
                            context.Position++;
                            textLength++;
                        }
                        if (!tag.IsEndTag)
                        {
                            var tagGrpStart = context.Position;
                            var tagGrup = new TagsGroup(tag);
                            if (tagGrup.Parse(context))
                            {
                                if (textLength > 0)
                                {
                                    if (this.Contents == null) this.Contents = new List<Match>();
                                    this.Contents.Add(new Text { Source = this.Source, Start = textStart, Length = textLength });
                                    textStart = context.Position;
                                    textLength = 0;
                                }
                                this.Contents.Add(tagGrup);
                            }
                            else
                            {
                                textLength += tag.Length;
                            }
                        }
                        else
                        {
                            if (tag.Name == this.OpenTag.Name)
                            {
                                if (textLength > 0)
                                {
                                    if (this.Contents == null) this.Contents = new List<Match>();
                                    this.Contents.Add(new Text { Source = this.Source, Start = textStart, Length = textLength });
                                    textStart = context.Position;
                                    textLength = 0;
                                }
                                this.CloseTag = tag;
                                return true;
                            }
                            else
                            {
                                textLength += tag.Length;
                            }
                        }
                    }
                }
                context.Position = startPos;
                return false;
            }
            public Tag OpenTag { get; set; }
            public Tag CloseTag { get; set; }
            public List<Match> Contents { get; set; }
        }
        class Text : Match
        {
            protected override bool ParseInternal(ParseContext context)
            {
                return true;
            }
        }
    }
}

如果您使用此代码,并且有一天发现您需要优化,因为解析器已变得模棱两可,请尝试在ParseContext中使用字典,请在此处查看更多信息:http://en.wikipedia.org/wiki/Top-down_parsing在主题自上而下解析的时间和空间复杂性。我发现它非常有趣。

答案 1 :(得分:1)

第一个更改非常简单 - 您可以通过将负责匹配自由文本的[^][]+更改为.来获取此更改。这似乎有点疯狂,但它实际上是安全的,因为你使用的是占有式组(?> ),所以所有有效的标签都会被第一次交替匹配 - \[(?<innertag>[^][/=\s]+)[^][]*] - 并且不能回溯和破坏标签。
(请记住启用单行标记,以便.匹配换行符)

第二个要求[unsuccessful]似乎违背了你的目标。从一开始,整个想法就是来匹配这些未闭合的标签。如果您允许未结算的代码,则 \[(.*?)\].*?[/\1]形式的所有匹配均有效。不好。充其量,您可以尝试将一些不允许匹配的标签列入白名单。

两种变化的例子:

(?>
\[ (?<tag>[^][/=\s]+) \s*
(?: = \s* (?<val>[^][]*) \s*)?
\]
)
  (?<content>
    (?>
       \[(?:unsuccessful)\]  # self closing
       |
       \[(?<innertag>[^][/=\s]+)[^][]*]
       |
       \[/(?<-innertag>\k<innertag>)]
       |
       .
    )*
    (?(innertag)(?!))
  )
\[/\k<tag>\]

Working example on Regex Hero

答案 2 :(得分:0)

确定。这是另一次尝试。这个有点复杂 我们的想法是将整个文本从start到ext匹配,并将其解析为单个Match。虽然很少使用.Net平衡组允许您微调您的捕获,记住所有位置并以您希望的方式捕获。
我想出的模式是:

\A
(?<StartContentPosition>)
(?:
    # Open tag
    (?<Content-StartContentPosition>)          # capture the content between tags
    (?<StartTagPosition>)                      # Keep the starting postion of the tag
    (?>\[(?<TagName>[^][/=\s]+)[^\]\[]*\])     # opening tag
    (?<StartContentPosition>)                  # start another content capture
    |
    # Close tag
    (?<Content-StartContentPosition>)          # capture the content in the tag
    \[/\k<TagName>\](?<Tag-StartTagPosition>)  # closing tag, keep the content in the <tag> group
    (?<-TagName>)
    (?<StartContentPosition>)                  # start another content capture
    |
    .           # just match anything. The tags are first, so it should match
                # a few if it can. (?(TagName)(?!)) keeps this in line, so
                # unmatched tags will not mess with the resul
)*
(?<Content-StartContentPosition>)          # capture the content after the last tag
\Z
(?(TagName)(?!))

请记住 - 自上次捕获(?<A-B>)以来,平衡组A会捕获B所有文本(并从B的堆栈中弹出该位置)。

现在您可以使用以下方法解析字符串:

Match match = Regex.Match(sample, pattern, RegexOptions.Singleline |
                                           RegexOptions.IgnorePatternWhitespace);

您感兴趣的数据将在match.Groups["Tag"].Captures上,其中包含所有标签(其中一些包含在其他标签中),match.Groups["Content"].Captures包含标签内容和标签之间的内容。例如,没有所有空格,它包含:

  • some code
  • some text
  • This is also an successful match.
  • This is also an [ unsuccessful match.
  • This is also an [unsuccessful] match.

这非常接近完整的解析文档,但您仍然需要使用索引和长度来确定文档的确切顺序和结构(尽管它并不比排序所有捕获更复杂)< / p>

此时我会陈述其他人所说的 - 这可能是编写解析器的好时机,这种模式并不漂亮......