C# 正则表达式基础

正则表达式

Regex类

元字符

正则表达式通常用来检查,检索,替换符合某个格式的文本


元字符:

正则表达式语言由两种基本字符组成

原义(正常)文本字符和元字符

元字符使用正则表达式具有处理能力.

^ 表示开头

$ 表示结尾

* 匹配0次或者多次

? 0 or 1

+ 1 or more

\w 表示字母数字下划线,汉字任意字符

\d 表示数字

\D 表示非数字

\s表示字符串

\S表示非空白字符

[\s\S] 表示任意字符

[\s\S]* 表示0到任意字符

[\s\S]*? 0个字符,匹配任意个字符前的次数

[a-A] 表示在某个范围内的字符,与指定区间内任何字符进行皮诶

\u4e00-\u9fa5 表示中文

| 或

() 分组

{n,m} 表示最少n最高m

{n,} 最少匹配n次

{n}  匹配前面的字符最少n次

[^X] 表示除了X除外任意字符



//演示在开头处拼接

string str = "大家好";

string newstr = Regex.Replace (str, "^", "首长:");

Console.WriteLine (newstr);

//演示在尾部处拼接

string newstr1 = Regex.Replace (str, "$", "啊");

Console.WriteLine (newstr1);


以数字开头中间有N个数字,以中文结尾.

string str1 = "124543好";

string newstr2 = @"^\d*[\u4e00-\u9fa5]$";

if (Regex.IsMatch (str1, newstr2)) {

Console.WriteLine ("匹配成功");

}

//匹配邮箱

string strl = "zhaoningyu@lanou3g.com";

string newstr3 = @"^\w+@\w+\.\w+$";

if (Regex.IsMatch (strl, newstr3)) {

Console.WriteLine ("匹配成功");

}



//检索特殊字符

string a = "#$4 16525";

string a1 = @"[^\s\w]+";

MatchCollection mc = Regex.Matches (a, a1);

Console.WriteLine (mc.Count);

foreach (Match item in mc) {

Console.WriteLine (item);

}



以上是正则表达式的一些基础用法.

推荐阅读 更多精彩内容