<<字符串高级截取和统计>>一文的C#正则实现
using System; using System.Text.RegularExpressions; namespace SubStringDemo { class Program { static void Main(string[] args) { string source = "123412355123559912323399"; string destString = "123"; Console.WriteLine("SubString count:" + SubString(source, destString)); Console.WriteLine("SubString 2th:" + SubString(source, destString, 2)); Console.WriteLine("" + SubString(source, destString, 4, 5)); Console.ReadLine(); } /// <summary> /// 统计源字符串中包含多少目标字符串 /// </summary> /// <param name="source">源字符串</param> /// <param name="dest">目标字符串</param> /// <returns>出现次数</returns> private static int SubString(string source, string dest) { MatchCollection mc = Regex.Matches(source, dest); return mc.Count; } /// <summary> /// 获取目标字符串在源字符串中指定出现次数的索引 /// </summary> /// <param name="source">源字符串</param> /// <param name="dest">目标字符串</param> /// <param name="ordinalNumber">出现序数</param> /// <returns>出现位置索引</returns> private static int SubString(string source, string dest, int ordinalNumber ) { MatchCollection mc = Regex.Matches(source, dest); if (mc.Count < ordinalNumber) { return -1; } else { return mc[ordinalNumber - 1].Index; } } /// <summary> /// 获取源字符串中在指定序数的目标字符串之后的字符串 /// </summary> /// <param name="source">源字符串</param> /// <param name="dest">目标字符串</param> /// <param name="ordinalNumber">出现序数</param> /// <param name="returnStringlength">返回字符串的长度</param> /// <returns>获取的字符串,不成功为null</returns> private static string SubString(string source, string dest, int ordinalNumber, int returnStringlength) { int pos = SubString(source, dest, ordinalNumber); if(pos != -1) { return source.Substring(pos + dest.Length, returnStringlength); } else { return null; } } } }
执行结果:
SubString count:4
SubString 2th:4
23399
posted on 2012-05-18 10:53 HOT SUMMER 阅读(233) 评论(0) 编辑 收藏 举报