正则表达式函数
1,
#region 输入input匹配pattern的第index分组 /// <summary> /// 输入input匹配pattern的第index分组 /// </summary> /// <param name="input">输入字符源</param> /// <param name="pattern">正则模式</param> /// <param name="index">第几个分组(分组用小括号)</param> /// <returns></returns> public static string MatchString(string input, string pattern, int index=0) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern); System.Text.RegularExpressions.Match match = regex.Match(input); if (match.Success) { return match.Groups[index].ToString(); } else { return null; } } #endregion
2,
#region 输入input匹配pattern的第index分组,输出所有匹配项 /// <summary> /// 输入input匹配pattern的第index分组,输出所有匹配项 /// </summary> /// <param name="input">输入字符源</param> /// <param name="pattern">正则模式</param> /// <param name="index">第几个分组(分组用小括号)</param> /// <returns>所有匹配项</returns> public static List<string> MatchStrings(string input,string pattern,int index=0) { List<string> list = new List<string>(); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern); System.Text.RegularExpressions.Match match = regex.Match(input); //循环匹配 while (match.Success) { list.Add(match.Groups[index].ToString()); match = match.NextMatch();//匹配下一个 } return list; } #endregion
总结: