首页 > 解决方案 > 文本、标签、base64 和 RegEx C#

问题描述

晚上好,我有一个正则表达式问题。

我读了一个json,文本的结构如下:

text[TAG1 attributes]othertext[/TAG1][TAG2 attributes]base64string[/TAG2]

我需要将最终文本提取为

text othertext base64string(decode)

输入文本可以是多行。

我该怎么做才能得到这个?

谢谢!

标签: c#regex

解决方案


这是一个应该与您的情况相匹配的正则表达式:

(?>^|\n|\[[^\]\n]*\]\n*)(?'content'[^\[]+)

正则表达式 101 演示

您基本上匹配[ornewline和之间的任何内容,直到]和开始在名为content的组中捕获内容,直到下一次出现。[

C#看起来像这样:

        var input = @"text[TAG1 attributes]othertext[/TAG1][TAG2 attributes]base64string[/TAG2]
text2[TAG1 attributes]othertext2[/TAG1][TAG2 attributes]base64string2[/TAG2]
text3[TAG1 attributes]othertext3[/TAG1][TAG2 attributes]base64string3[/TAG2]";

        var expression = new Regex(@"(?>^|\n|\[[^\]\n]*\]\n*)(?'content'[^\[]+)");
        Match match = expression.Match(input);
        while (match.Success)
        {
            var content = match.Groups["content"].Value;
            Console.WriteLine(content);
            match = match.NextMatch();
        }

.Net 小提琴演示

阅读有关Match.Groups的 MS 文档。


推荐阅读