C# 正则表达式捕获捕获组的所有引用(不使用全局修饰符)
我有一个xml数据库,结构如下:C# 正则表达式捕获捕获组的所有引用(不使用全局修饰符),c#,.net,regex,C#,.net,Regex,我有一个xml数据库,结构如下: <mydatabase id="list01"> <entryA author="none" desc="nothing"> Text. </entryA> <entryB type="tag"> More Text. </entryB> <entryA> Some text. </entr
<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
}
我使用regex获取informationcode+示例:,但是匹配中的标记和值在最后捕获的匹配中只出现一次
这是正则表达式:
<entry[A|B|C](?: (?'tag'(?:[a-z|A-Z])*?)="(?'value'.*?)")*?>\n\s*?(?'text'\S.*?)\n\s*?<\/entry[A|B|C]>
如何使用正则表达式获得每个匹配的整个标记列表及其值
是的,我可以在标签周围添加另一个捕获组,并用regex再次处理文本,但这似乎是多余的,因为它们已经匹配
编辑:我不想使用XML解析器。使用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());
}
}
}
如果您正在使用XML,那么您可能需要考虑使用实际的XML解析器,而不是将所有内容作为文本和使用正则表达式读取。在这里尝试使用正则表达式只会让你头疼。还要看看如何创建一个正则表达式,也就是说,将信息添加到实际问题中,而不是添加到外部站点上。我正在从事一个教育性项目,我想解析所有类型的结构类似的数据库。这既不难也不是不可能,我只是好奇这件我可以优化的小事。简言之:不,我不想使用XML解析器。@我编辑了这个问题以包含正则表达式。我最初没有把它包括在这里,因为在我看来,它在那个网站上更具可读性和相关性。我将来会记住这一点: