正则表达式

Posted on 2019-04-27 16:24  金色的省略号  阅读(425)  评论(0编辑  收藏  举报

正则表达式

 https://docs.microsoft.com/zh-cn/dotnet/api/system.text.regularexpressions?view=netframework-4.8

 

 1 using System;
 2 using System.Text.RegularExpressions;
 3 
 4 class Test
 5 {
 6     static void  Main()
 7     {
 8         //1.
 9         string pattern = @"^[\. a-zA-z]+ (?<name>\w+), [a-zA-z]+, x(?<ext>\d+)$";
10         Regex rx = new Regex( pattern );
11         
12         //2.
13         string [] sa =
14         {
15             "Dr. David Jones, Ophthalmology, x2441",
16 
17             "Ms. Cindy Harriman, Registry, x6231",
18 
19             "Mr. Chester Addams, Mortuary, x1667",
20 
21             "Dr. Hawkeye Pierce, Surgery, x0986",
22         };
23     
24         foreach ( string s in sa )
25         {
26             Match m = rx.Match(s);
27 
28             if( m.Success )
29                 Console.Write( m.Result("${ext}, $1") );
30             
31             //public string Replace (string input, string replacement);
32             Console.WriteLine( "\t" +
33                     rx.Replace( s, "姓:${name}, 分机号:${ext}" )
34                 );
35         }
36     }
37 }