C#中如何使用正则表达式
【草稿版本,谨慎阅读】
参考文档:正则表达式30分钟入门教程
如需系统学习正则表达式内容,请移步上述教程。
正则表达式按照指定的规则来匹配字符或字符串。\’.\’ \’ \b\’ \’ \d\’等等被称为是正则表达式中的元字符,比如说点元字符用来匹配换行符以外的其他任意字符,\b元字符用来匹配单词,\s元字符用来匹配空格等等。
正则表达式转换:
Show you the code:(\S)
1 string input = "I is Lily."; 2 string pattern = @"\s+"; 3 string replacement = " "; 4 string result = Regex.Replace(input, pattern, replacement); 5 6 Console.WriteLine("Original String: {0}", input); 7 Console.WriteLine("Replacement String: {0}", result);
\s用来匹配空格,而\s+则是用来匹配一个或多个和空格,如代码所示,将一个或多个空格,替换成一个空格,运行效果如图:
Show you the code:(\b)
1 string input = "I is Lily."; 2 string pattern = @"\bis\b"; 3 string replacement = "am"; 4 string result = Regex.Replace(input, pattern, replacement); 5 Console.WriteLine("Original String: {0}", input); 6 Console.WriteLine("Replacement String: {0}", result);
\b用来匹配单词,则\bis\b用来匹配单词is,并将is替换成am,运行效果如图:
Show you the code:(.*)
input = "Sis a girlD"; pattern = @"is\b.*\bgirl"; replacement = "*"; result = Regex.Replace(input, pattern, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String: {0}", result);
.*用来匹配任意数量的非换行字符,则pattern匹配以is开头girl结尾,且is后面和girl前面必须紧邻空格的字符串,运行效果如图:
验证正则表达式是否匹配:
Show you the code:(\d)
1 string phone = ""; 2 string pattern = @"1\d{10}"; 3 bool result = false; 4 Console.WriteLine("请输入你的手机号码"); 5 do 6 { 7 phone = Console.ReadLine(); 8 result = Regex.IsMatch(phone, pattern); 9 if (!result) 10 Console.WriteLine("BadNum,try again"); 11 } while (!result); 12 Console.WriteLine("Good");
\d用来匹配一位数字,则d{10}用来匹配10位数字,运行效果如下:
持续更新中…
常见正则表达式元字符:
1:\w 匹配任意的字母,数字或者下划线,则\w+匹配一位或多位字符、数字等。