一个数字组成的字符串要求有3种结果
比如
01237289391274444
一找出重复出现了两次的数字,并且不重复出现
结果:1379
二找出出现2次以上的数字,并且替换掉重复的数字
24
三找出没有重复出现的数字
08
弄得头都大了,正则太差了,求救,以及学习正则的资料
比如
01237289391274444
一找出重复出现了两次的数字,并且不重复出现
结果:1379
二找出出现2次以上的数字,并且替换掉重复的数字
24
三找出没有重复出现的数字
08
弄得头都大了,正则太差了,求救,以及学习正则的资料
{
string s = "01237289391274444";
Console.WriteLine("只出现一次的:" + new string(GetRepeat(s, RepeatSearchType.single)));
Console.WriteLine("只出现两次的:" + new string(GetRepeat(s, RepeatSearchType.two)));
Console.WriteLine("出现多次的 :" + new string(GetRepeat(s, RepeatSearchType.more)));
Console.ReadKey();
}public enum RepeatSearchType { single, two, more }
public static char[] GetRepeat(string s,RepeatSearchType rst)
{
Match m = Regex.Match(s, "(?:(0)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9))+");
List<char> result = new List<char>();
for (int i = 1; i <= 10; i++)
{
switch (rst)
{
case RepeatSearchType.single:
if (m.Groups[i].Captures.Count == 1) result.Add(m.Groups[i].Value[0]);
break;
case RepeatSearchType.two:
if (m.Groups[i].Captures.Count == 2) result.Add(m.Groups[i].Value[0]);
break;
case RepeatSearchType.more:
if (m.Groups[i].Captures.Count > 2) result.Add(m.Groups[i].Value[0]);
break;
}
}
return result.ToArray();
}输出只出现一次的:08
只出现两次的:1379
出现多次的 :24
void Main()
{
string s = "01237289391274444";
var query = from t in s.ToCharArray()
group t by t into m
select new
{
m.Key,
count=m.Count()
};
Console.WriteLine("出现两次的有:");
foreach (var q in query.Where(q => q.count == 2))
{
Console.WriteLine(q.Key);
}
Console.WriteLine("出现多于两次的有:");
foreach (var q in query.Where(q => q.count > 2))
{
Console.WriteLine(q.Key);
}
Console.WriteLine("出现一次的有:");
foreach (var q in query.Where(q => q.count == 1))
{
Console.WriteLine(q.Key);
}
}/*
出现两次的有:
1
3
7
9
出现多于两次的有:
2
4
出现一次的有:
0
8*/
group s by s.c into g
where g.Count() == 2 && g.Max(v => v.i) - g.Min(v => v.i) != 1
select g; Console.WriteLine("重复两次,不相邻");
foreach (var v in Query)
{
Console.WriteLine(v.Key);
}
Console.WriteLine("\r\n重复两次一次的:");
var Query1 = from s in str.ToCharArray().Select((c, i) => new { c, i })
group s by s.c into g
where g.Count() > 2
select g;
foreach (var v in Query1)
{
Console.WriteLine(v.Key);
str = str.Replace(v.Key.ToString(), "");
} Console.WriteLine(str);
Console.WriteLine("\r\n没有重复出现的:");
var Query2 = from s in str.ToCharArray().Select((c, i) => new { c, i })
group s by s.c into g
where g.Count() ==1
select g;
foreach (var v in Query2)
{
Console.WriteLine(v.Key);
} /*
重复两次,不相邻
1
3
7
9 重复两次一次的:
2
4
00137893917 没有重复出现的:
8
*/