NET基础学习笔记9-正值表达式

mac2022-06-30  83

正值表达式

正则表达式元字符

《1》  .  除\n任何的单个字符

《2》 [] 表示中间的任意一个字符如a[0-9 a-z]b  →  a9b

《3》  |  或   z|hello  表示z或者是hello,而不是zello或者hello→(z|h)ello

《4》  ()改变优先级,提取组。

《5》  *   限定符,表示前面的表达式可以出现0次或多次。(可有可无)。

《6》  +   限定符,至少出现1次。可以出现多次。

《7》  ?   限定符,表示出现0次或者1次。【终结贪婪模式】

《8》  {n} 限定前面的表达式,必须出现n次。{n,m}  至少出现n次,最多出现m次。{n,}至少出现n次。

《9》    ^  匹配一个正则表达式的开头

《10》   $  匹配一个正则表达式的结尾

简写

\d  表示0-9;

\D  表示除了0-9以外的。\d的反面

\s  空白符。

\S 表示非空的字符。 \s的反面

\w 匹配字母或者数字或下划线或汉字,即能组成单词的字符,除了%&#@!$等字符[a-zA-Z0-9_汉字]

\W 非\w ,等同于[^\w]%

 

使用 regex类 正则表达式

using System.Text.RegularExpressions;使用的类库

Regex.IsMatch();//判断一个字符串是否匹配某一个正则表达式。

Regex.Match();//从某一个字符串中提取匹配正则表达式的某个子字符串(只能提取一个)

Regex.Matches();//字符串提取,可以提取所有匹配的字符串。

Regex.Replace();//字符串替换,把所有匹配正则表达式的字符串替换为对应的字符串。

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 7 namespace 正则表达式 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //#region Regex.IsMatch(); 14 //string reg = "^b.+123$"; 15 //bool b = Regex.IsMatch("b8111afasdfsad111123", reg); //. 表示单个字符 \n除外 16 //Console.WriteLine(b); 17 18 //#endregion 19 20 //#region 例子 21 //Console.WriteLine(Regex.IsMatch("bbbbg", "^b.*g$")); //匹配 22 //Console.WriteLine(Regex.IsMatch("bg", "^b.*g$")); //匹配 23 //Console.WriteLine(Regex.IsMatch("gege", "^b.*g$")); //不匹配 24 //#endregion 25 26 //#region |例子 27 //while (true) 28 //{ 29 // //string regex="r|food";//匹配 r food 30 // string regex = "^(r|food)$"; //匹配 r food 31 // Console.WriteLine("请输入一个字符串"); 32 // string str = Console.ReadLine(); 33 // Console.WriteLine(Regex.IsMatch(str,regex)); 34 //} 35 //#endregion 36 37 //#region 身份证号码验证 38 //while (true) 39 //{ 40 // Console.WriteLine("请输入身份证号码"); 41 // string reg = @"^(\d{15}|\d{18})$"; 42 // string s = Console.ReadLine(); 43 // Console.WriteLine(Regex.IsMatch(s, reg)); 44 //} 45 46 //#endregion 47 48 // #region 验证电话号码 49 // //string reg = @"a\.b";//正则表达式中的转义符也是\,如果要出现一0个字符,这个字符也是“元字符” 50 // 这时候为了让元字符,系统不认为是元字符,就需要将元字符转义。 51 // //string s = "aab"; 52 // //Console.WriteLine(Regex.IsMatch(s,reg)); 53 54 // //验证下面的电话号码 55 //// 010-8888888或010-88888880或010xxxxxxx 56 //// 0335-8888888或0335-88888888(区号-电话号) 57 ////10086、10010、95595、95599、95588(5位) 58 //// 13888888888(11位都是数字) 59 // string reg = @"^((\d{3,4}\-?\d{7,8})|(\d{5}))$"; 60 // while (true) 61 // { 62 // Console.WriteLine("输入一个电话号码"); 63 // string s=Console.ReadLine(); 64 // Console.WriteLine(Regex.IsMatch(s,reg)); 65 // } 66 67 // #endregion 68 69 #region 邮箱地址是否合法 70 while (true) 71 { 72 Console.WriteLine("请输入邮箱"); 73 string reg = @"[a-zA-Z0-9][a-zA-Z0-9_\.]+@[0-9a-zA-Z]+(\.([0-9a-zA-Z])+)+$"; 74 string s = Console.ReadLine(); 75 Console.WriteLine(Regex.IsMatch(s, reg)); 76 } 77 78 #endregion 79 80 Console.ReadKey(); 81 } 82 } 83 } 正则表达式练习例子

 

转载于:https://www.cnblogs.com/huijie/p/3239809.html

最新回复(0)