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”. 问题是如果我们 ...
随机推荐
- oracle监听的动态注册和静态注册
参考资料: https://blog.csdn.net/tianlesoftware/article/details/5543166 https://www.cnblogs.com/guilingya ...
- [Kubernetes]CentOS7下搭建Harbor仓库
环境依赖: Harbor仓库需要环境:Python 2.7或以上版本,Docker 1.10或以上,Docker Compose 1.6.0或以上. CentOS7自带Python,所以不需要安装. ...
- selenium中,8种 find element 方法
-*- coding;utf-8 -*- from selenium import webdriver dr = webdriver.Chrome() dr.get("https://www ...
- mysql多表关联update修改操作
UPDATE province_yunnan_salary s1 JOIN province_guangdong_salary s2 ON s1.user_name= s2.user_name S ...
- 51nod--1298 (计算几何基础)
题目: 1298 圆与三角形 题目来源: HackerRank 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注 给出圆的圆心和半径,以及三角形的三个顶点,问圆 ...
- django配置发送邮箱
该邮箱配置后台发送邮箱验证使用 settings内配置 # 服务器地址 EMAIL_HOST = 'smtp.163.com' # 端口,邮箱默认动态端口 25 EMAIL_PORT = 25 # 邮 ...
- ModelSerializer序列化(Apiview)
url部分: url(r'^book/$',views.book.as_view()),url(r'^books/(\d+)/$', views.bookdetail.as_view(),name=' ...
- python-socket编程(入门,网络基础)
一.网络基础 网络建立的目的是为了数据交互(通信) 如何实现通信: 1.建立好底层的物理连接介质 2.有一套统一的通信标准,称之为互联网协议 1.osi七层协议 互联网协议按照功能的不同分为osi七层 ...
- C# Winform控件对透明图片重叠时导致图片不透明的解决方法(转)
在Winform中如果将一个透明图片放在窗体上能正常显示透明,但是如果将该图片放在另一个控件上会导致不能显示透明效果. 解决这种情况,可以采取在控件上使用GDI+绘画出透明图片. 这里我们就以一个pi ...
- python 面向对象编程(高级篇)
飞机票 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使用(可以讲多函数中公用的变量封装到对象中) 对象,根据模板创建的实例(即:对 ...