有一段时间,正则表达式学习很火热很潮流,当时在CSDN一天就能看到 好几个正则表达式的帖子,那段时间借助论坛以及Wrox Press出版的《C#字符串和正则表达式参考手册》学习了一些基础的知识,同时也为我在CSDN大概赚了1000分,今天想起来,去找《C#字符串和正 则表达式参考手册》时,已经不知所踪了。现在用到正则的时候也比较少,把以前的笔记等整理一下,以志不忘。

(1)“@”符号
“@”虽然并非C#正则表达式的“成员”,但是它经常与C#正则表达式出双入对。“@”表示,跟在它后面的字符串是个“逐字字符串”,不是很好理解,举个例子,以下两个声明是等效的:
string x="D:\\My Huang\\My Doc";
string y = @"D:\My Huang\My Doc";
事实上,如果按如下声明,C#将会报错,因为“\”在C#中用于实现转义,如“\n”换行:
string x = "D:\My Huang\My Doc";

(2)基本的语法字符。
\d  0-9的数字
\D  \d的补集(以所以字符为全集,下同),即所有非数字的字符
\w  单词字符,指大小写字母、0-9的数字、下划线
\W  \w的补集
\s  空白字符,包括换行符\n、回车符\r、制表符\t、垂直制表符\v、换页符\f
\S  \s的补集
.  除换行符\n外的任意字符
[…]  匹配[]内所列出的所有字符
[^…]  匹配非[]内所列出的字符
下面提供一些简单的示例:


string i = "\n";
string m = "3";
Regex r = new Regex(@"\D");
//同Regex r = new Regex("\\D");
//r.IsMatch(i)结果:true
//r.IsMatch(m)结果:false

string i = "%";
string m = "3";
Regex r = new Regex("[a-z0-9]");
//匹配小写字母或数字字符
//r.IsMatch(i)结果:false
//r.IsMatch(m)结果:true

(3)定位字符
“定位字符”所代表的是一个虚的字符,它代表一个位置,你也可以直观地认为“定位字符”所代表的是某个字符与字符间的那个微小间隙。
^  表示其后的字符必须位于字符串的开始处
$  表示其前面的字符必须位于字符串的结束处
\b  匹配一个单词的边界
\B  匹配一个非单词的边界
另外,还包括:\A  前面的字符必须位于字符处的开始处,\z  前面的字符必须位于字符串的结束处,\Z  前面的字符必须位于字符串的结束处,或者位于换行符前
下面提供一些简单的示例:


string i = "Live for nothing,die for something";
Regex r1 = new Regex("^Live for nothing,die for something$");
//r1.IsMatch(i) true
Regex r2 = new Regex("^Live for nothing,die for some$");
//r2.IsMatch(i) false
Regex r3 = new Regex("^Live for nothing,die for some");
//r3.IsMatch(i) true

string i = @"Live for nothing,
die for something";//多行
Regex r1 = new Regex("^Live for nothing,die for something$");
Console.WriteLine("r1 match count:" + r1.Matches(i).Count);//0
Regex r2 = new Regex("^Live for nothing,die for something$", RegexOptions.Multiline);
Console.WriteLine("r2 match count:" + r2.Matches(i).Count);//0
Regex r3 = new Regex("^Live for nothing,\r\ndie for something$");
Console.WriteLine("r3 match count:" + r3.Matches(i).Count);//1
Regex r4 = new Regex("^Live for nothing,$");
Console.WriteLine("r4 match count:" + r4.Matches(i).Count);//0
Regex r5 = new Regex("^Live for nothing,$", RegexOptions.Multiline);
Console.WriteLine("r5 match count:" + r5.Matches(i).Count);//0
Regex r6 = new Regex("^Live for nothing,\r\n$");
Console.WriteLine("r6 match count:" + r6.Matches(i).Count);//0
Regex r7 = new Regex("^Live for nothing,\r\n$", RegexOptions.Multiline);
Console.WriteLine("r7 match count:" + r7.Matches(i).Count);//0
Regex r8 = new Regex("^Live for nothing,\r$");
Console.WriteLine("r8 match count:" + r8.Matches(i).Count);//0
Regex r9 = new Regex("^Live for nothing,\r$", RegexOptions.Multiline);
Console.WriteLine("r9 match count:" + r9.Matches(i).Count);//1
Regex r10 = new Regex("^die for something$");
Console.WriteLine("r10 match count:" + r10.Matches(i).Count);//0
Regex r11 = new Regex("^die for something$", RegexOptions.Multiline);
Console.WriteLine("r11 match count:" + r11.Matches(i).Count);//1
Regex r12 = new Regex("^");
Console.WriteLine("r12 match count:" + r12.Matches(i).Count);//1
Regex r13 = new Regex("$");
Console.WriteLine("r13 match count:" + r13.Matches(i).Count);//1
Regex r14 = new Regex("^", RegexOptions.Multiline);
Console.WriteLine("r14 match count:" + r14.Matches(i).Count);//2
Regex r15 = new Regex("$", RegexOptions.Multiline);
Console.WriteLine("r15 match count:" + r15.Matches(i).Count);//2
Regex r16 = new Regex("^Live for nothing,\r$\n^die for something$", RegexOptions.Multiline);
Console.WriteLine("r16 match count:" + r16.Matches(i).Count);//1
//对于一个多行字符串,在设置了Multiline选项之后,^和$将出现多次匹配。

string i = "Live for nothing,die for something";
string m = "Live for nothing,die for some thing";
Regex r1 = new Regex(@"\bthing\b");
Console.WriteLine("r1 match count:" + r1.Matches(i).Count);//0
Regex r2 = new Regex(@"thing\b");
Console.WriteLine("r2 match count:" + r2.Matches(i).Count);//2
Regex r3 = new Regex(@"\bthing\b");
Console.WriteLine("r3 match count:" + r3.Matches(m).Count);//1
Regex r4 = new Regex(@"\bfor something\b");
Console.WriteLine("r4 match count:" + r4.Matches(i).Count);//1
//\b通常用于约束一个完整的单词

(4)重复描述字符
“重复描述字符”是体现C#正则表达式“很好很强大”的地方之一:
{n}  匹配前面的字符n次
{n,}  匹配前面的字符n次或多于n次
{n,m}  匹配前面的字符n到m次
?  匹配前面的字符0或1次
+  匹配前面的字符1次或多于1次
*  匹配前面的字符0次或式于0次
以下提供一些简单的示例:


string x = "1024";
string y = "+1024";
string z = "1,024";
string a = "1";
string b="-1024";
string c = "10000";
Regex r = new Regex(@"^\+?[1-9],?\d{3}$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//1
Console.WriteLine("z match count:" + r.Matches(z).Count);//1
Console.WriteLine("a match count:" + r.Matches(a).Count);//0
Console.WriteLine("b match count:" + r.Matches(b).Count);//0
Console.WriteLine("c match count:" + r.Matches(c).Count);//0
//匹配1000到9999的整数。

(5)择一匹配
C#正则表达式中的 (|)
符号似乎没有一个专门的称谓,姑且称之为“择一匹配”吧。事实上,像[a-z]也是一种择一匹配,只不过它只能匹配单个字符,而(|)则提供了更大的范
围,(ab|xy)表示匹配ab或匹配xy。注意“|”与“()”在此是一个整体。下面提供一些简单的示例:


string x = "0";
string y = "0.23";
string z = "100";
string a = "100.01";
string b = "9.9";
string c = "99.9";
string d = "99.";
string e = "00.1";
Regex r = new Regex(@"^\+?((100(.0+)*)|([1-9]?[0-9])(\.\d+)*)$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//1
Console.WriteLine("z match count:" + r.Matches(z).Count);//1
Console.WriteLine("a match count:" + r.Matches(a).Count);//0
Console.WriteLine("b match count:" + r.Matches(b).Count);//1
Console.WriteLine("c match count:" + r.Matches(c).Count);//1
Console.WriteLine("d match count:" + r.Matches(d).Count);//0
Console.WriteLine("e match count:" + r.Matches(e).Count);//0
//匹配0到100的数。最外层的括号内包含两部分“(100(.0+)*)”,“([1-9]?[0-9])(\.\d+)*”,这两部分是“OR”的关系,即正则表达式引擎会先尝试匹配100,如果失败,则尝试匹配后一个表达式(表示[0,100)范围中的数字)。

(6)特殊字符的匹配
下面提供一些简单的示例:


string x = "\\";
Regex r1 = new Regex("^\\\\$");
Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1
Regex r2 = new Regex(@"^\\$");
Console.WriteLine("r2 match count:" + r2.Matches(x).Count);//1
Regex r3 = new Regex("^\\$");
Console.WriteLine("r3 match count:" + r3.Matches(x).Count);//0
//匹配“\”

string x = "\"";
Regex r1 = new Regex("^\"$");
Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1
Regex r2 = new Regex(@"^""$");
Console.WriteLine("r2 match count:" + r2.Matches(x).Count);//1
//匹配双引号

(7)组与非捕获组
以下提供一些简单的示例:


string x = "Live for nothing,die for something";
string y = "Live for nothing,die for somebody";
Regex r = new Regex(@"^Live ([a-z]{3}) no([a-z]{5}),die \1 some\2$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//0
//正则表达式引擎会记忆“()”中匹配到的内容,作为一个“组”,并且可以通过索引的方式进行引用。表达式中的“\1”,用于反向引用表达式中出现的第一个组,即粗体标识的第一个括号内容,“\2”则依此类推。

string x = "Live for nothing,die for something";
Regex r = new Regex(@"^Live for no([a-z]{5}),die for some\1$");
if (r.IsMatch(x))
{
    Console.WriteLine("group1 value:" + r.Match(x).Groups[1].Value);//输出:thing
}
//获取组中的内容。注意,此处是Groups[1],因为Groups[0]是整个匹配的字符串,即整个变量x的内容。

string x = "Live for nothing,die for something";
Regex r = new Regex(@"^Live for no(?<g1>[a-z]{5}),die for some\1$");
if (r.IsMatch(x))
{
    Console.WriteLine("group1 value:" + r.Match(x).Groups["g1"].Value);//输出:thing
}
//可根据组名进行索引。使用以下格式为标识一个组的名称(?<groupname>…)。

string x = "Live for nothing nothing";
Regex r = new Regex(@"([a-z]+) \1");
if (r.IsMatch(x))
{
    x = r.Replace(x, "$1");
    Console.WriteLine("var x:" + x);//输出:Live for nothing
}
//删除原字符串中重复出现的“nothing”。在表达式之外,使用“$1”来引用第一个组,下面则是通过组名来引用:
string x = "Live for nothing nothing";
Regex r = new Regex(@"(?<g1>[a-z]+) \1");
if (r.IsMatch(x))
{
    x = r.Replace(x, "${g1}");
    Console.WriteLine("var x:" + x);//输出:Live for nothing
}

string x = "Live for nothing";
Regex r = new Regex(@"^Live for no(?:[a-z]{5})$");
if (r.IsMatch(x))
{
    Console.WriteLine("group1 value:" + r.Match(x).Groups[1].Value);//输出:(空)
}
//在组前加上“?:”表示这是个“非捕获组”,即引擎将不保存该组的内容。

(8)贪婪与非贪婪
正则表达式的引擎是贪婪,只要模式允许,它将匹配尽可能多的字符。通过在“重复描述字符”(*,+)后面添加“?”,可以将匹配模式改成非贪婪。请看以下示例:


string x = "Live for nothing,die for something";
Regex r1 = new Regex(@".*thing");
if (r1.IsMatch(x))
{
    Console.WriteLine("match:" + r1.Match(x).Value);//输出:Live for nothing,die for something
}
Regex r2 = new Regex(@".*?thing");
if (r2.IsMatch(x))
{
    Console.WriteLine("match:" + r2.Match(x).Value);//输出:Live for nothing
}

(9)回溯与非回溯
使用“(?>…)”方式进行非回溯声明。由于正则表达式引擎的贪婪特性,导致它在某些情况下,将进行回溯以获得匹配,请看下面的示例:


string x = "Live for nothing,die for something";
Regex r1 = new Regex(@".*thing,");
if (r1.IsMatch(x))
{
    Console.WriteLine("match:" + r1.Match(x).Value);//输出:Live for nothing,
}
Regex r2 = new Regex(@"(?>.*)thing,");
if (r2.IsMatch(x))//不匹配
{
    Console.WriteLine("match:" + r2.Match(x).Value);
}
//在r1中,“.*”由于其贪婪特性,将一直匹配到字符串的最后,随后匹配“thing”,但在匹配“,”时失败,此时引擎将回溯,并在“thing,”处匹配成功。
在r2中,由于强制非回溯,所以整个表达式匹配失败。

(10)正向预搜索、反向预搜索
正向预搜索声明格式:正声明 “(?=…)”,负声明 “(?!...)” ,声明本身不作为最终匹配结果的一部分,请看下面的示例:


string x = "1024 used 2048 free";
Regex r1 = new Regex(@"\d{4}(?= used)");
if (r1.Matches(x).Count==1)
{
    Console.WriteLine("r1 match:" + r1.Match(x).Value);//输出:1024
}
Regex r2 = new Regex(@"\d{4}(?! used)");
if (r2.Matches(x).Count==1)
{
    Console.WriteLine("r2 match:" + r2.Match(x).Value); //输出:2048
}
//r1中的正声明表示必须保证在四位数字的后面必须紧跟着“ used”,r2中的负声明表示四位数字之后不能跟有“ used”。

反向预搜索声明格式:正声明“(?<=)”,负声明“(?<!)”,声明本身不作为最终匹配结果的一部分,请看下面的示例:


string x = "used:1024 free:2048";
Regex r1 = new Regex(@"(?<=used:)\d{4}");
if (r1.Matches(x).Count==1)
{
    Console.WriteLine("r1 match:" + r1.Match(x).Value);//输出:1024
}
Regex r2 = new Regex(@"(?<!used:)\d{4}");
if (r2.Matches(x).Count==1)
{
    Console.WriteLine("r2 match:" + r2.Match(x).Value);//输出:2048
}
//r1中的反向正声明表示在4位数字之前必须紧跟着“used:”,r2中的反向负声明表示在4位数字之前必须紧跟着除“used:”之外的字符串。

(11)十六进制字符范围
正则表达式中,可以使用 "\xXX" 和 "\uXXXX" 表示一个字符("X" 表示一个十六进制数)形式字符范围:
\xXX       编号在 0到255 范围的字符,比如:空格可以使用 "\x20" 表示。
\uXXXX   任何字符可以使用 "\u" 再加上其编号的4位十六进制数表示,比如:汉字可以使用“[\u4e00-\u9fa5]”表示。

(12)对[0,100]的比较完备的匹配
下面是一个比较综合的示例,对于匹配[0,100],需要特殊考虑的地方包括
*00合法,00.合法,00.00合法,001.100合法
*空字符串不合法,仅小数点不合法,大于100不合法
*数值是可带后缀的,如“1.07f”表示该值为一个float类型(未考虑)


Regex r = new Regex(@"^\+?0*(?:100(\.0*)?|(\d{0,2}(?=\.\d)|\d{1,2}(?=($|\.$)))(\.\d*)?)$");
string x = "";
while (true)
{
    x = Console.ReadLine();
    if (x != "exit")
    {
        if (r.IsMatch(x))
        {
            Console.WriteLine(x + " succeed!");
        }
        else
        {
            Console.WriteLine(x + " failed!");
        }
    }
    else
    {
        break;
    }
}

(13)精确匹配有时候是困难的
有些需求要做到精确匹配比较困难,例如:日期、Url、Email地址等,其中一些你甚至需要研究一些专门的文档写出精确完备的表达式,对于这种情况,只
能退而求其次,保证比较精确的匹配。例如对于日期,可以基于应用系统的实际情况考虑一段较短的时间,或者对于像Email的匹配,可以只考虑最常见的形
式。

.NET进阶系列之一:C#正则表达式整理备忘的更多相关文章

  1. [转].NET进阶系列之一:C#正则表达式整理备忘

    本文转自:http://www.cnblogs.com/KissKnife/archive/2008/03/23/1118423.html 有一段时间,正则表达式学习很火热很潮流,当时在CSDN一天就 ...

  2. Thinkphp 整理备忘 杂记

    1:输出变量函数  (手册目录:控制器-输出变量) I('变量类型.变量名',['默认值'],['过滤方法'],['额外数据源']) 例:$title = I('post.title','','str ...

  3. 整理备忘一波liunx命令(持续更新)

    # 分区挂载 查看当前目录下的文件大小 du --max-depth= -h # 文件操作 # 编辑操作 #liunx 字体设置 苹果方字体下载安装 # 网洛端口 netstat命令各个参数说明如下: ...

  4. Redis集群搭建详细过程整理备忘

    三.安装配置 1.环境 使用2台centos服务器,每台机器上部署3个实例,集群为三个主节点与三个从节点: 192.168.5.144:6380 192.168.5.144:6381 192.168. ...

  5. 超全PHP学习资源整理:入门到进阶系列

    PHP是少数几门在语言层面饱受诟病,但在实际开发和应用上却又让人无法撒手的语言之一.就好比路边摊小吃,一遍骂人家不卫生,一遍却又说:真香.所谓接地气,不外如此,大道理不说,PHP光是轮子多.市场占有率 ...

  6. DotNet进阶系列

    一. 回顾历史 回顾个人发展历程,自2012年初次接触开发至今(2018年)已经有六个年头,这期间陆陆续续学习并掌握了不少技术,C#语言.ORM框架.多线程技术.设计模式.前端技术.MVC.MVVM框 ...

  7. Ext JS学习第十六天 事件机制event(一) DotNet进阶系列(持续更新) 第一节:.Net版基于WebSocket的聊天室样例 第十五节:深入理解async和await的作用及各种适用场景和用法 第十五节:深入理解async和await的作用及各种适用场景和用法 前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、G

    code&monkey   Ext JS学习第十六天 事件机制event(一) 此文用来记录学习笔记: 休息了好几天,从今天开始继续保持更新,鞭策自己学习 今天我们来说一说什么是事件,对于事件 ...

  8. C#进阶系列——WebApi 路由机制剖析:你准备好了吗?

    前言:从MVC到WebApi,路由机制一直是伴随着这些技术的一个重要组成部分. 它可以很简单:如果你仅仅只需要会用一些简单的路由,如/Home/Index,那么你只需要配置一个默认路由就能简单搞定: ...

  9. 【 D3.js 进阶系列 】 进阶总结

    进阶系列的文章从去年10月开始写的,晃眼又是4个多月了,想在年前总结一下. 首先恭祝大家新年快乐.今年是羊年吧.前段时间和朋友聊天,聊到十二生肖里为什么没猫,我张口就道:不是因为十二生肖开会的时候猫迟 ...

随机推荐

  1. js基础-需要注意的地方

    ---因为跟别的语言很像,所以只记录要注意的地方 1.== 和 === 的区别 ===要求类型也相等 "5"==5 = ture "5"===5 = false ...

  2. ubuntu 快捷图标

    ubuntu的图标都存在 /usr/share/applications下 图标是Desktop的后缀 首先gedit /usr/share/applications/xx.Desktop xx为应用 ...

  3. XML 解析中,如何排除控制字符

    XML 解析中,如何排除控制字符 今天在解析一个中文的 XML时,始终报错 PCDATA invalid Char value 21 in Entity ,查询了一下这个 21 的ascii 值,发现 ...

  4. Unity-资源

    模型.材质.动画 Unity的默认系统单位为"米" 三维软件 三维软件内部米制尺寸/m 默认设置导入Unity中的尺寸/m 与Unity单位的比例关系 Maya 1 100 1:1 ...

  5. SQL Server 数据类型 Decimal介绍

    为SQL Server 数据类型,属于浮点数类型.存储数据范围是: -1038~1038-1 的固定精度和小数位的数字.一个decimal类型的数据占用了2~17个字节.decimal数据类型在SQL ...

  6. 何时可以开启透明数据加密(TDE)?

    TDE可以为我们的数据库提供加密保护,但是,不是任何情况下都可以随意开启TDE的,同时开启TDE后,我们的数据库维护管理工作也需要进行一些调整. 下面我们就先看看开启TDE需要的条件吧! 无法正常开启 ...

  7. Sticks(Central Europe 1995) (DFS)

    Sticks(Central Europe 1995) Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d &am ...

  8. 百度定位SDK:弥补Android基站WIFI定位缺失

    http://tech.qq.com/a/20120524/000347.htm 如今,基于位置信息的移动应用越来越多,从餐饮.购物等本地生活服务,到定向广告的匹配.移动社交网络的构建,LBS类应用的 ...

  9. Delphi中的异常处理(10种异常来源、处理、精确处理)

    一.异常的来源 在Delphi应用程序中,下列的情况都比较有可能产生异常. 1.文件处理 2.内存分配 3.windows资源 4.运行时创建对象和窗体 5.硬件和操作系统冲突 6.网络问题 7.数据 ...

  10. C# 如何查看源程序的IL代码

    1.打开microsoft  visual  studio  2008  /  visual  studio  tools /  visual  studio  2008 命令提示  ,并输入ilda ...