正则表达式号称开发者得瑞士军刀,使用好正则表达式尤其重要。

拆分多个正则:

 public static string[] SplitByManyRegex(string text, string[] subRegexStrings)
{
string allRegexString = "^(?<mySubGroup0>.*?)";
for (int i = 0; i < subRegexStrings.Length; i++)
{
allRegexString += "(?<mySubGroup" + (i + 1) + ">" + subRegexStrings[i] + ".*?)";
}
allRegexString += "$"; Regex subRegex = new Regex(allRegexString, RegexOptions.Singleline | RegexOptions.IgnoreCase);
MatchCollection mc = subRegex.Matches(text);
if (mc.Count <= 0)
{
return new string[] { text };
} List<int> positions = new List<int>();
for (int m = 0; m < subRegexStrings.Length + 1; m++)
{
positions.Add(mc[0].Groups["mySubGroup" + m].Index);
} List<string> result = new List<string>(); for (int i = 0; i < positions.Count; i++)
{
int nextPos = 0;
if (i < positions.Count - 1) nextPos = positions[i + 1];
else nextPos = text.Length;
result.Add(text.Substring(positions[i], nextPos - positions[i]));
}
return result.ToArray();
}

  调用:

string[] tags = { "【答案】", "【解析】" };

  拆分单个正则:

 public static string[] SplitByRegex(string text, string subRegexString)
{
Regex subRegex = new Regex(subRegexString, RegexOptions.Singleline | RegexOptions.IgnoreCase);
MatchCollection mc = subRegex.Matches(text);
if (mc.Count <= 0)
{
return new string[] { text };
} List<int> positions = new List<int>();
for (int m = 0; m < mc.Count; m++)
{
positions.Add(mc[m].Index);
} List<string> result = new List<string>();
result.Add(text.Substring(0, positions[0])); for (int i = 0; i < positions.Count; i++)
{
int nextPos = 0;
if (i < mc.Count - 1) nextPos = positions[i + 1];
else nextPos = text.Length;
result.Add(text.Substring(positions[i], nextPos - positions[i]));
} return result.ToArray();
}

  不反回第一条:

public static string[] SplitByRegexNoFirtPart(string text, string subRegexString)
{
string[] ary = SplitByRegex(text, subRegexString);
return TrimFirstElementOfArray(ary);
} private static string[] TrimFirstElementOfArray(string[] ary)
{
if (ary == null || ary.Length == 0) return new string[0];
string[] result = new string[ary.Length - 1];
for (int i = 1; i < ary.Length; i++) result[i - 1] = ary[i];
return result;
}

  拆分如:(A(B(C?)?)?)

  public static string[] SplitByManyRegex_MayLess(string text, string[] subRegexStrings)
{
string allRegexString = "^(?<mySubGroup0>.*?)"; for (int i = 0; i < subRegexStrings.Length; i++)
{
allRegexString += "((?<mySubGroup" + (i + 1) + ">" + subRegexStrings[i] + ".*?)";
}
for (int i = subRegexStrings.Length-1; i >=0 ; i--)
{
allRegexString += "?)";
} allRegexString += "$"; Regex subRegex = new Regex(allRegexString, RegexOptions.Singleline | RegexOptions.IgnoreCase);
MatchCollection mc = subRegex.Matches(text);
if (mc.Count <= 0)
{
return new string[] { text };
} List<int> positions = new List<int>();
for (int m = 0; m < subRegexStrings.Length + 1; m++)
{
if (mc[0].Groups["mySubGroup" + m].Success)
{
positions.Add(mc[0].Groups["mySubGroup" + m].Index);
}
} List<string> result = new List<string>(); for (int i = 0; i < positions.Count; i++)
{
int nextPos = 0;
if (i < positions.Count - 1) nextPos = positions[i + 1];
else nextPos = text.Length;
result.Add(text.Substring(positions[i], nextPos - positions[i]));
}
return result.ToArray();
}

  可以任意顺序,任意个数:

  public static string[] SplitByManyRegex_AnyOrder(string text, string[] subRegexStrings, bool resultChangeOrder = true )
{
if(string.IsNullOrEmpty(text) || subRegexStrings==null || subRegexStrings.Length == 0)
{
return new string[] { text };
} string allReg = "(" + string.Join("|", subRegexStrings) + ")";
string[] result = SplitByRegex(text, allReg); if (!resultChangeOrder) return result; string[] ordered = new string[subRegexStrings.Length+1];
ordered[0] = result[0];
for(int i=1; i<result.Length; i++)
{
//将某部分放到对应的正则顺序
for(int k=0; k< subRegexStrings.Length; k++)
{
if(Regex.Match( result[i], subRegexStrings[k]).Success)
{
ordered[k+1] = result[i];
}
}
//如果某个没有找到则保持为null
}
return ordered;
}

  用正则表达式替换文本中的内容:

 public static string TranformHandAnswer(string html)
{
string strReg = "(?<hand>(<handanswer>(.*?)</handanswer>))"; //正则表达式
Regex regex = new Regex(strReg, RegexOptions.Singleline | RegexOptions.IgnoreCase); int _subjectOrderNum = subjectOrderNum; //TODO: Lambda不允许ref变量,这里临时这样用
html = regex.Replace(html, (Match match) =>
{
string handContent = match.Groups["hand"].Value;
string result = “替换得文本” return result;
}); return html;
}

  有以上几个辅助类,在难得正则拆分都能搞定。

C#正则Groups高级使用方法的更多相关文章

  1. 与正则有关的JS方法结合其在项目中的应用

    与正则有关的JS方法结合其在项目中的应用 前言 最近项目中用到正则匹配比较多,因此打算深入理解和总结下各个与正则有关的方法,再结合在项目中使用的情况.与正则有关的JS方法共有7个,分别是RegExp对 ...

  2. js正则验证数字的方法

    正则验证数字的方法: <script type="text/javascript"> function validate(){ var reg = new RegExp ...

  3. Vue 事件的高级使用方法

    Vue 事件的高级使用方法 事件方法 在Vue中提供了4中事件监听方法,分别是: $on(event: string | Array, fn) $emit(event: string) $once(e ...

  4. 缓存需要注意的问题以及使用.net正则替换字符串的方法

    参考资料:http://www.infoq.com/cn/news/2015/09/cache-problems 正则替换字符串的简单方法: var regTableType = new Regex( ...

  5. no plugin found for prefix 'tomcat 7' in the current project and in the plugin groups的解决方法

    解决方法一: 找到这个settings.xml文件,进行编辑,在pluginGroups标签下加入下面的配置 <pluginGroups><pluginGroup>org.ap ...

  6. javaScript prototype实例(正则) 自定义日期格式化方法

    一个JS自定义日期格式化方法,包括了不少知识点,以下方法来自jQuery DataTable中文的官方参考 //return (new Date(data)).Format("yyyy-MM ...

  7. 正则匹配之replace方法

    在我印象中,replace方法就是一个正则匹配,然后一股脑的替换掉匹配到的内容的一个方法. 在一次任务需求中,有这么一个需求,一行字符串里面,替换相应字符串,具体就是匹配到‘A’然后把‘A’替换成‘a ...

  8. Lambda--Optional、Collectors高级进阶方法

    Lambda--Collectors.optional高级使用 偶然看到了同事groupingBy用法,然后百度衍生出了optional,collectors,map等各种用法.突然发现自己之前写的代 ...

  9. jquery 中$.post获取MVC Controller中JsonResult返回包含LIst<Model>类型的子List<Model>的高级使用方法

    比如JsonResult中返回return Json(models);的models结构如下: models返回含有四个集合的序列,每个集合的序列中又包含一个子集合序列“Child”. 问题是如果我们 ...

随机推荐

  1. flirtlib 测试过程

    一. 安装flirtlib 1. 安装必要的依赖库 Boost >= 1.36 (submodules math and graph) 这个有了 Qt4 (for the gui)这个也有了 Q ...

  2. [BugBounty] Sleeping stored Google XSS Awakens a $5000 Bounty

    来源:https://blog.it-securityguard.com/bugbounty-sleeping-stored-google-xss-awakens-a-5000-bounty/ 理解 ...

  3. 【转】python之random模块分析(一)

    [转]python之random模块分析(一) random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): ...

  4. Vivado Turtorial 01 —— 使用vivado中debug功能(类似ISE中ChipScope)

    1.基于BASYS3板子,有如下代码: module top( input clk, input rst, output test_clk ); parameter DIV_CNT = 2; reg ...

  5. LwIP Application Developers Manual1---介绍

    1.前言 本文主要是对LwIP Application Developers Manual的翻译 2.读者(应用开发手册的读者) 谁适合读这份手册 网络应用的开发者 想了解lwIP的网络应用开发者 阅 ...

  6. python3+selenium入门15-执行JavaScript

    有时有些功能需要通过js来执行,比如拖动浏览器的滚动条.通过execute_script()方法可以执行js的代码 window.scrollTo()可以传两个参数,第一个参数是下方滚动条的位置,第二 ...

  7. hibernate框架学习之数据查询(QBC)

    lQBC(Query By Criteria)是一种Hibernate中使用面向对象的格式进行查询的计数 lQBC查询方式步骤 •获取Session对象 •初始化Criteria对象(使用Sessio ...

  8. 微信小程序采坑(一)

    1.微信小程序如何让text内容空格 <text decode="{{true}}" space="{{true}}">  </text> ...

  9. java压缩图片质量

    使用了工具thumbnailator,据说thumbnailator是一个非常好的图片开源工具,使用起来很方便.不过没仔细看过,我只是需要压缩图片,让其占用空间变小而已.使用maven引入jar包 & ...

  10. 7-Links

    Use the <a> element to define a link Use the href attribute to define the link address Use the ...