博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《.Net 基础系列》- 正则
阅读量:7021 次
发布时间:2019-06-28

本文共 2019 字,大约阅读时间需要 6 分钟。

hot3.png

项目结构

135941_Za6r_2330610.png

贪婪模式

string inputMsg = "111。11。1。";Match match = Regex.Match(inputMsg, ".+?。");// 111。MatchCollection collection = Regex.Matches(inputMsg, "(.+?)。");Match item1 = collection[0];// 111。Match item2 = collection[1];// 11。Match item3 = collection[2];// 1。

常用正则

string inputMsg = "绿色家园01栋02单元0304号";MatchCollection collection = Regex.Matches(inputMsg, @"(\D+)(\d+)(\D+)(\d+)(\D+)(\d+)(\D+)");string item1 = collection[0].Groups[1].Value;// 绿色家园string item2 = collection[0].Groups[2].Value;// 01string item3 = collection[0].Groups[3].Value;// 栋string item4 = collection[0].Groups[4].Value;// 02string item5 = collection[0].Groups[5].Value;// 单元string item6 = collection[0].Groups[6].Value;// 0304string item7 = collection[0].Groups[7].Value;// 号

反向引用

string inputMsg = "我我我我我爱爱爱爱你你你";inputMsg = Regex.Replace(inputMsg, @"(.)\1+", "$1");// 我爱你

基本元字符

Match match1 = Regex.Match("abc", ".+");Match match2 = Regex.Match("abc", "a[bB]c");Match match3 = Regex.Match("aBc", "a[^0-9a-z]c");Match match4 = Regex.Match("abc", "a(B|b)c");Match match5 = Regex.Match("abc", "abc*");Match match6 = Regex.Match("a123b", "a[0-9]{3}b");Match match7 = Regex.Match("a123b", "a[0-9]{3,4}b");Match match8 = Regex.Match("a123b", "a[0-9]{3,}b");Match match9 = Regex.Match("abc123", "^abc");Match match10 = Regex.Match("abc123", "123$");//等价于	[0-9]Match match11 = Regex.Match("a123b", @"a\d+b");//等价于	[0-9a-zA-Z]  在C# 中还包括中文字符Match match12 = Regex.Match("Aabc3B", @"A\w+B");//表示所有那些空白符,不可见字符,包括 换行,tab,空格Match match13 = Regex.Match("abc    b c", @"abc\s+b\s+c");

IsMatch

bool b1 = Regex.IsMatch("a123c", "^a.+c$");

匹配转移字符

//\\\\dstring msg = Regex.Escape("\\d");

Replace

//我的生日是2010-05-21耶我的生日是2000-03-11耶string msg1 = "我的生日是05/21/2010耶我的生日是03/11/2000耶";msg1 = Regex.Replace(msg1, @"(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2");//hello 【welcome】 to 【China】, hello 【welcome】 to 【China】string msg2 = "hello 'welcome' to 'China', hello 'welcome' to 'China'";msg2 = Regex.Replace(msg2, @"'(.+?)'", @"【$1】");

 

转载于:https://my.oschina.net/kimisme/blog/1596089

你可能感兴趣的文章
linux下串口控制
查看>>
马尔科夫链简介
查看>>
VC++ 的MFC 和ATL 及COM 是什么?
查看>>
.NET泛型04,使用Lazy<T>实现延迟加载
查看>>
ASP.NET MVC中的Session以及处理方式
查看>>
想知道美国大学按计算机专业的排名,以及各大学在计算机哪个方面是强项,应该去哪里查找?...
查看>>
[C# 网络编程系列]专题六:UDP编程
查看>>
DNGuard 使用介绍
查看>>
HDU 4419 Colourful Rectangle(线段树)
查看>>
webservice接口的开发和调用
查看>>
Z-order curve
查看>>
ADO.NET的主要组件
查看>>
用Excel打开csv格式文件并生成相应图形
查看>>
【uTenux实验】内存池管理(固定内存池和可变内存池)
查看>>
Android——Android Studio的一些小技巧(转)
查看>>
Linux Linux程序练习二
查看>>
angular run()运行块
查看>>
javascript中的两个定时函数setTimeOut()和setInterVal()的区别
查看>>
如何检测NFC芯片型号?NFC手机即可!
查看>>
Android 8款开源游戏引擎
查看>>