C#正则Groups高级使用方法
正则表达式号称开发者得瑞士军刀,使用好正则表达式尤其重要。
拆分多个正则:
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高级使用方法的更多相关文章
- 与正则有关的JS方法结合其在项目中的应用
与正则有关的JS方法结合其在项目中的应用 前言 最近项目中用到正则匹配比较多,因此打算深入理解和总结下各个与正则有关的方法,再结合在项目中使用的情况.与正则有关的JS方法共有7个,分别是RegExp对 ...
- js正则验证数字的方法
正则验证数字的方法: <script type="text/javascript"> function validate(){ var reg = new RegExp ...
- Vue 事件的高级使用方法
Vue 事件的高级使用方法 事件方法 在Vue中提供了4中事件监听方法,分别是: $on(event: string | Array, fn) $emit(event: string) $once(e ...
- 缓存需要注意的问题以及使用.net正则替换字符串的方法
参考资料:http://www.infoq.com/cn/news/2015/09/cache-problems 正则替换字符串的简单方法: var regTableType = new Regex( ...
- no plugin found for prefix 'tomcat 7' in the current project and in the plugin groups的解决方法
解决方法一: 找到这个settings.xml文件,进行编辑,在pluginGroups标签下加入下面的配置 <pluginGroups><pluginGroup>org.ap ...
- javaScript prototype实例(正则) 自定义日期格式化方法
一个JS自定义日期格式化方法,包括了不少知识点,以下方法来自jQuery DataTable中文的官方参考 //return (new Date(data)).Format("yyyy-MM ...
- 正则匹配之replace方法
在我印象中,replace方法就是一个正则匹配,然后一股脑的替换掉匹配到的内容的一个方法. 在一次任务需求中,有这么一个需求,一行字符串里面,替换相应字符串,具体就是匹配到‘A’然后把‘A’替换成‘a ...
- Lambda--Optional、Collectors高级进阶方法
Lambda--Collectors.optional高级使用 偶然看到了同事groupingBy用法,然后百度衍生出了optional,collectors,map等各种用法.突然发现自己之前写的代 ...
- jquery 中$.post获取MVC Controller中JsonResult返回包含LIst<Model>类型的子List<Model>的高级使用方法
比如JsonResult中返回return Json(models);的models结构如下: models返回含有四个集合的序列,每个集合的序列中又包含一个子集合序列“Child”. 问题是如果我们 ...
随机推荐
- unity实现剧情对话
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { private string show ...
- jquery获取浏览器URL参数
getRequestParams:function(param){ var reg = new RegExp("(^|&)" + param + "=([^&am ...
- RS485 通信接收时丢失0x11等数据
RS485通信接收方,丢弃掉了值为 0x11 的数据. 怀疑 0x11 被转义,没有按照原始数据接收, 查看ASCII码对应表 0x11 代表 “本文结束”, 因此丢弃是有可能的. 要想接收原始数据而 ...
- Fiddler模拟低速网络
1. 打开 Rules -> Customize Rules,ctrl + F 找 300 2.修改上传.下载速度,保存 ctrl + s 3.启动模拟网络限速 4.想要取消模拟网络限速,取消勾 ...
- android SDK与ADT版本更新问题
android SDK与ADT版本更新问题 问题:This Android SDK requires Android Developer Toolkit version 14.0.0 or above ...
- HNUOJ 13341
题目给你一个串, 串是严格的 1 – n 的排列,里面的数是随机的 把这个串里面的数字分别输出//先预处理,对于给出的串能找到里面的最大数,再 DFS 处理 #include<iostream& ...
- tcp和udp协议的聊天 和udp协议的时间同步机制-----编码
tcp协议聊天 服务端:: 客户端 udp协议的聊天 ############ udp协议 ########### 服务器 import socket sk = socket.socket(type ...
- 实体类和json互相转换
/// <summary> /// 将实体类转换为json数据 /// </summary> /// <returns></returns> publi ...
- Spring Boot (一): Spring Boot starter自定义
前些日子在公司接触了spring boot和spring cloud,有感于其大大简化了spring的配置过程,十分方便使用者快速构建项目,而且拥有丰富的starter供开发者使用.但是由于其自动化配 ...
- Protobuf3 语法指南
目录 [−] 定义一个消息类型 指定字段类型 分配标识号 指定字段规则 添加更多消息类型 添加注释 保留标识符(Reserved) 从.proto文件生成了什么? 标量数值类型 默认值 枚举 使用其他 ...