输入 - 字符串:"TAG1xxxTAG2yyyTAG3zzzTAG1tttTAG1bbb"
预期结果:成对TAG1 = {xxx,,ttt,bbb}, TAG2 = {yyy}, TAG3 = {zzz}.
我是使用regexp完成的,但我真的很困惑使用Regex.Replace而不使用返回值。我想改进这段代码,那怎么能实现呢?
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace TermsTest
{
class Program
{
static void Main(string[] args)
{
string[] tags = { "TAG1", "TAG2", "TAG3", "TAG4", "TAG5", "TAG6", "TAG7", "TAG8" };
string file = "TAG2jjfjfjndbfdjTAG1qqqqqqqTAG3uytygh fhdjdfTAG5hgjdhfghTAG6trgfmxc hdfhdTAG2jfksksdhjskTAG3kdjbjvbsjTAG2jskjdjdvjvbxjkvbjdTAG2jkxcndjcjbkjn";
string tag = "(" + string.Join("|", tags) + ")";
var dictionary = new Dictionary<string, List<string>>(tags.Length);
Regex.Replace(file, string.Format(@"({0})(.+?)(?={0}|$)", tag), match =>
{
string key = match.Groups[1].Value, value = match.Groups[3].Value;
if (dictionary.ContainsKey(key))
dictionary[key].Add(value);
else
dictionary[key] = new List<string> {value};
return "";
});
foreach (var pair in dictionary)
{
Console.Write(pair.Key + " =\t");
foreach (var entry in pair.Value)
{
Console.Write(entry + " ");
}
Console.WriteLine();
Console.WriteLine();
}
}
}
}
答案 0 :(得分:3)
string input = "TAG1xxxTAG2yyyTAG3zzzTAG1tttTAG1bbb";
var lookup = Regex.Matches(input, @"(TAG\d)(.+?)(?=TAG|$)")
.Cast<Match>()
.ToLookup(m => m.Groups[1].Value, m => m.Groups[2].Value);
foreach (var kv in lookup)
{
Console.WriteLine(kv.Key + " => " + String.Join(", ", kv));
}
输出:
TAG1 => xxx, ttt, bbb
TAG2 => yyy
TAG3 => zzz
答案 1 :(得分:0)
这是.NET CaptureCollection对象的完美工作 - 一种独特的.NET功能,可让您多次重复使用同一个捕获组。
使用此正则表达式并使用Matches
创建MatchCollection:
(?:TAG1(.*?(?=TAG|$)))?(?:TAG2(.*?(?=TAG|$)))?(?:TAG3(.*?(?=TAG|$)))?
然后检查捕获:
Groups[1].Captures
将包含所有TAG1 Groups[2].Captures
将包含所有TAG2 Groups[3].Captures
将包含所有TAG3 从那里开始,你的最终数据结构只有很短的一步。
为了减少回溯的可能性,您可以使令牌成为原子:
(?>(?:TAG1(.*?(?=TAG|$)))?)(?>(?:TAG2(.*?(?=TAG|$)))?)(?>(?:TAG3(.*?(?=TAG|$)))?)
有关其工作原理的详细信息,请参阅Capture Groups that can be Quantified。
答案 2 :(得分:0)
您要做的只是对同一标记的值进行分组,因此使用GroupBy
方法应该更容易:
string input = "TAG1xxxTAG2yyyTAG3zzzTAG1tttTAG1bbb";
var list = Regex.Matches(input, @"(TAG\d+)(.+?)(?=TAG\d+|$)")
.Cast<Match>()
.GroupBy(m => m.Groups[1].Value,
(key, values) => string.Format("{0} = {output
}",
key,
string.Join(", ",
values.Select(v => v.Groups[2]))));
var output = string.Join(", ", list);
这会产生"TAG1 = {xxx, ttt, bbb}, TAG2 = {yyy}, TAG3 = {zzz}"
字符串{{1}}
答案 3 :(得分:0)
我不确定我是否知道你在这个问题上的所有假设和惯例;但这给了我类似的结果:
var tagColl = string.Join("|", tags);
var tagGroup = string.Format("(?<tag>{0})(?<val>[a-z]*)", tagColl);
var result = from x in Regex.Matches(file, tagGroup).Cast<Match>()
where x.Success
let pair = new { fst = x.Groups["tag"].Value, snd = x.Groups["val"].Value }
group pair by pair.fst into g
select g;
一个简单的测试就是:
Console.WriteLine(string.Join("\r\n", from g in result
let coll = string.Join(", ", from item in g select item.snd)
select string.Format("{0}: {{{1}}}", g.Key, coll)));