C#正则表达式整理备忘

2009年4月30日星期四

C#正则表达式整理备忘

(4)重复描述字符
重复描述字符是体现C#正则表达式很好很强大的地方之一:
{n}匹配前面的字符n次
{n,}匹配前面的字符n次或多于n次
{n,m}匹配前面的字符n到m次
?匹配前面的字符0或1次
+匹配前面的字符1次或多于1次
*匹配前面的字符0次或式于0次
以下提供一些简单的示例:Code
stringx=1024;
stringy=+1024;
stringz=1,024;
stringa=1;
stringb=-1024;
stringc=10000;
Regexr=newRegex(@^\+?[1-9],?\d{3}$);
Console.WriteLine(xmatchcount:+r.Matches(x).Count);//1
Console.WriteLine(ymatchcount:+r.Matches(y).Count);//1
Console.WriteLine(zmatchcount:+r.Matches(z).Count);//1
Console.WriteLine(amatchcount:+r.Matches(a).Count);//0
Console.WriteLine(bmatchcount:+r.Matches(b).Count);//0
Console.WriteLine(cmatchcount:+r.Matches(c).Count);//0
//匹配1000到9999的整数。


(5)择一匹配
C#正则表达式中的(|)符号似乎没有一个专门的称谓,姑且称之为择一匹配吧。事实上,像[a-z]也是一种择一匹配,只不过它只能匹配单个字符,而(|)则提供了更大的范围,(ab|xy)表示匹配ab或匹配xy。注意|与()在此是一个整体。下面提供一些简单的示例:Code
stringx=0;
stringy=0.23;
stringz=100;
stringa=100.01;
stringb=9.9;
stringc=99.9;
stringd=99.;
stringe=00.1;
Regexr=newRegex(@^\+?((100(.0+)*)|([1-9]?[0-9])(\.\d+)*)$);
Console.WriteLine(xmatchcount:+r.Matches(x).Count);//1
Console.WriteLine(ymatchcount:+r.Matches(y).Count);//1
Console.WriteLine(zmatchcount:+r.Matches(z).Count);//1
Console.WriteLine(amatchcount:+r.Matches(a).Count);//0
Console.WriteLine(bmatchcount:+r.Matches(b).Count);//1
Console.WriteLine(cmatchcount:+r.Matches(c).Count);//1
Console.WriteLine(dmatchcount:+r.Matches(d).Count);//0
Console.WriteLine(ematchcount:+r.Matches(e).Count);//0
//匹配0到100的数。最外层的括号内包含两部分(100(.0+)*),([1-9]?[0-9])(\.\d+)*,这两部分是OR的关系,即正则表达式引擎会先尝试匹配100,如果失败,则尝试匹配后一个表达式(表示[0,100)范围中的数字)。



(6)特殊字符的匹配
下面提供一些简单的示例:Code
stringx=\\;
Regexr1=newRegex(^\\\\$);
Console.WriteLine(r1matchcount:+r1.Matches(x).Count);//1
Regexr2=newRegex(@^\\$);
Console.WriteLine(r2matchcount:+r2.Matches(x).Count);//1
Regexr3=newRegex(^\\$);
Console.WriteLine(r3matchcount:+r3.Matches(x).Count);//0
//匹配\

stringx=\;
Regexr1=newRegex(^\$);
Console.WriteLine(r1matchcount:+r1.Matches(x).Count);//1
Regexr2=newRegex(@^$);
Console.WriteLine(r2matchcount:+r2.Matches(x).Count);//1
//匹配双引号

||浏览()|(0)最近读者:网友评论:发表评论:姓名:*姓名最长为50字节网址或邮箱:(选填)内容:验证码:请点击后输入四位验证码,字母不区分大小写

0 评论:

发表评论