首页 文章

正则表达式捕获所有出现的捕获组(不使用全局修饰符)

提问于
浏览
-4

我有一个像这样结构的xml数据库:

<mydatabase id="list01">
    <entryA author="none" desc="nothing">
        Text.
    </entryA>
    <entryB type="tag">
        More Text.
    </entryB>
    <entryA>
        Some text.
    </entryA>
</mydatabase>

从这个数据库我想提取一个条目列表:

class Entry{
   KeyValuePair<string, string>[] attributes; // the attributes key="value"
   string text; //The inner text
}

我正在使用正则表达式来获取信息(代码示例:https://regex101.com/r/nI1hY8/2),但匹配中的标记和值仅在最后捕获的匹配项中出现一次 .

这是正则表达式:

<entry[A|B|C](?: (?'tag'(?:[a-z|A-Z])*?)="(?'value'.*?)")*?>\n\s*?(?'text'\S.*?)\n\s*?<\/entry[A|B|C]>

如何使用正则表达式获取每个匹配的标记及其值的完整列表?

附:是的我可以在标签周围添加另一个捕获组,并使用正则表达式再次处理文本,但这似乎是多余的,因为它们已经匹配 .

编辑:我不想使用XML解析器 .

1 回答

  • 1

    使用xml Linq

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApplication6
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                //using unique keys
                Dictionary<string, string> dict1 = doc.Descendants("mydatabase").FirstOrDefault().Elements()
                    .GroupBy(x => x.Name.LocalName, y => ((string)y).Trim())
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
    
                //when there are duplicate keys
                Dictionary<string, List<string>> dict2 = doc.Descendants("mydatabase").FirstOrDefault().Elements()
                    .GroupBy(x => x.Name.LocalName, y => ((string)y).Trim())
                    .ToDictionary(x => x.Key, y => y.ToList());
    
    
            }
        }
    }
    

相关问题