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

拆分多个正则:

 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. Error "Client wants topic A to have B, but our version has C. Dropping connection."

    ROS problem 出现这个问题的原因是话题上的消息类型和订阅节点指定的消息类型不匹配.

  2. keepalived的vip无法ping通【原创】

    今天收到redis的keepalived vip无法ping通的告警,查看服务器和服务时发现vip在服务器上,服务也正常.只能在本机ping通,跨网段无法ping通.切换keepalived vip至 ...

  3. Windows PowerShell 入門(4)-変数と演算子

    Windows PowerShellにおける変数と演算子の使用方法について学びます.今回は代表的な演算子として.算術演算子.代入演算子.論理演算子.比較演算子.範囲演算子.置換演算子.ビット演算子.型 ...

  4. axios请求接口的踩坑之路

    1.跨域问题除了前端安装插件还需要后端php设置,设置如下 Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, ...

  5. python3+requests库框架设计04-配置文件

    python3配置文件的增删改查等操作可以使用内置的ConfigParser模块,可以自行百度学习,也可以看Python3学习笔记27-ConfigParser模块 配置文件一般存放着环境信息,比如u ...

  6. 模拟电路学习之NMOS开关电路1

  7. 重新配置ocr voting

    由于存储空间不足,下线的数据库需要把存储空间腾出来,关闭集群资源,主机工程师收回lun需要(包括ocr 和 voting data 磁盘组),新的应用需要上线需要新的数据库,新的hitach存储到位需 ...

  8. Ubuntu解除"输入密码以解锁密钥环”

    解决办法有两种: 1.去掉默认密钥环的密码: 打开应用程序->附件->密码和加密密钥(如果你的没有,在终端中输入 seahorse),切换到密码选项卡,会看到一个密码密钥环(我的密钥环是 ...

  9. mysql优化——show processlist命令详解

    SHOW PROCESSLIST显示哪些线程正在运行 不在mysql提示符下使用时用mysql -uroot  -e 'Show  processlist'   或者   mysqladmin pro ...

  10. GZip、deflate和sdch压缩(网摘整理)

    GZip和deflate: gzip是一种数据格式,默认且目前仅使用deflate算法压缩data部分:deflate是一种压缩算法,是huffman编码的一种加强. deflate与gzip解压的代 ...