轻松学习C#的正则表达式
在编写处理字符串的程序时,经常会有查找符合某些复杂规则的字符串的需要。正则表达式就是用于描述这些规则的工具。正则表达式拥有一套自己的语法规则,常见语法包括字符匹配,重复匹配,字符定位,转义匹配和其他高级语法(字符分组,字符替换和字符决策),使用正则表达式时,首先构造正则表达式,这就用到了Regex类。其构造方式有两种:
一、正则表达式的匹配 <span style="font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions;//引入命名空间 using System.Threading.Tasks; namespace 正则表达式 { class Program { static void Main(string[] args) { string str = @"(0530|0530-)d{7,8}";//定义的正则表达式符合条件为“0530”或 Console.WriteLine("请输入一个电话号码");//“0530-”开头,后面跟7位或8位数字 string tel = Console.ReadLine(); bool b; b = Regex.IsMatch(tel,str);//判断是否符合正则表达式 if (b) { Console.WriteLine("{0}是某地的电话号码",tel); } else { Console.WriteLine("{0}不是某地的电话号码",tel); } Console.ReadLine(); } } }</span> 输入:0530-12345678 <span style="font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string str = @"w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*";//定义的电子邮件地址的正则表达式 Console.WriteLine("请输入一个正确的Internet电子邮件地址"); string email = Console.ReadLine(); bool b; b = Regex.IsMatch(email,str);//判断是否符合正则表达式 if (b) { string outstr = ""; outstr = Regex.Replace(email,"@","AT");//进行替换 Console.WriteLine("替换后为:{0}",outstr); } else { Console.WriteLine("你所输入的字符串中不包括Internet URL"); } Console.ReadLine(); } } }</span> 输入:123456@126.com <span style="font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string str = ";";//定义的正则表达式 Console.WriteLine("请输入多个用户姓名,以分号隔开"); string names = Console.ReadLine(); string[] name; name = Regex.Split(names,str); Console.WriteLine("分隔后的姓名为:"); foreach (string item in name) { Console.WriteLine(item); } Console.ReadLine(); } } }</span> 输入:张三;李四;王五 以上就是C#的正则表达式,希望对大家的学习有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |