代码改变世界

C#学习笔记(十二):正则表达式

2015-07-15 13:42  阿诚de窝  阅读(321)  评论(0编辑  收藏  举报

Regex

正则表达式的类,我们可以通过该类来使用正则表达式。

比如下面我们使用Regex来判断输入的字符串是否符合指定的格式:

 1 using System;
 2 using System.Text.RegularExpressions;
 3 
 4 namespace Study
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             string[] strs = new[] {"111-22-3333", "444-5-6666"};
11             string patten = @"^\d{3}-\d{2}-\d{4}$";
12 
13             foreach (string str in strs)
14             {
15                 if (Regex.IsMatch(str, patten))
16                 {
17                     Console.WriteLine(str);
18                 }
19             }
20 
21             Console.ReadKey();
22         }
23     }
24 }

运行发现返回的是“111-22-3333”。

Match和Group

我们如果需要得到匹配的信息,则会使用到Match类,该类记录了字符串中的所有符合的匹配项的匹配信息。

而如果需要得到匹配项中的分组则可以使用Group属性。

下面我们来看一个具体的例子,该例子是我目前工作中遇到的一个扯淡的问题,具体就是要把类似"heroData.name = "Li Lei";"和"string name = heroData.name;"替换为Java类型的写法,如"heroData.setName("Li Lei");"和"string name = heroData.getName();",由于量太大,所以如果手改,我估计我会死的,那么下面我们就用C#的正则表达式来帮我们自动完成这个过程,代码如下,带有注释大家自己看了:

  1 using System;
  2 using System.Text.RegularExpressions;
  3 
  4 namespace Study
  5 {
  6     class Program
  7     {
  8         //要处理的代码
  9         private const string CODE = @"
 10 
 11 //我是设置示例代码
 12 HeroData heroData = new HeroData();
 13 heroData.name = ""LiLei"";
 14 heroData.age = 18;
 15 heroData.skill = SkillData.datas[0];
 16 heroData.PlaySkill();
 17 
 18 //我是不应该被替换的
 19 skillInfo.name = ""DaJueZhao"";
 20 
 21 //我是读取的示例代码
 22 string name = heroData.name;
 23 int age = heroData.age;
 24 Debug.Log(""Name: "" + name + "", Age: "" + age);
 25 
 26 ";
 27 
 28         //我们需要设定一个前缀来保证匹配的精确
 29         private const string PREFIX = "heroData";
 30 
 31         static void Main(string[] args)
 32         {
 33             string result;
 34 
 35             result = ProcessSet(CODE, PREFIX);
 36             result = ProcessGet(result, PREFIX);
 37 
 38             Console.Write(result);
 39 
 40             Console.ReadKey();
 41         }
 42 
 43         private static string ProcessSet(string code, string prefixName)
 44         {
 45             string result = code;
 46 
 47             //用于匹配的表达式
 48             string patten = prefixName + @"\.([0-9a-zA-Z_$]*)\s*=\s*([0-9a-zA-Z_$""\.\[\]]*)\s*;";
 49             //string patten = prefixName + "\\.([0-9a-zA-Z_$]*)\\s*=\\s*([0-9a-zA-Z_$"\\.\\[\\]]*)\\s*;";  //不用 @ 的写法
 50 
 51             Match match = Regex.Match(code, patten);
 52             //存在匹配项
 53             while (match.Success)
 54             {
 55                 //获取整个匹配的字符串
 56                 string allStr = match.Groups[0].Value;
 57                 //获取属性名称
 58                 string attrName = match.Groups[1].Value;
 59                 //获取值
 60                 string attrValue = match.Groups[2].Value;
 61 
 62                 //获取修改后的字符串
 63                 string modifyStr = prefixName + ".set" + FirstCharUpper(attrName) + "(" + attrValue + ");";
 64 
 65                 //替换
 66                 result = result.Replace(allStr, modifyStr);
 67 
 68                 //查询下一个匹配项
 69                 match = match.NextMatch();
 70             }
 71 
 72             return result;
 73         }
 74 
 75         private static string ProcessGet(string code, string prefixName)
 76         {
 77             string result = code;
 78 
 79             //用于匹配的表达式
 80             string patten = prefixName + @"\.([0-9a-zA-Z_$]*)\s*;";
 81             //string patten = prefixName + "\\.([0-9a-zA-Z_$]*)\\s*;";  //不用 @ 的写法
 82 
 83             Match match = Regex.Match(code, patten);
 84             //存在匹配项
 85             while (match.Success)
 86             {
 87                 //获取整个匹配的字符串
 88                 string allStr = match.Groups[0].Value;
 89                 //获取属性名称
 90                 string attrName = match.Groups[1].Value;
 91 
 92                 //获取修改后的字符串
 93                 string modifyStr = prefixName + ".get" + FirstCharUpper(attrName) + "();";
 94 
 95                 //替换
 96                 result = result.Replace(allStr, modifyStr);
 97 
 98                 //查询下一个匹配项
 99                 match = match.NextMatch();
100             }
101 
102             return result;
103         }
104 
105         private static string FirstCharUpper(string str)
106         {
107             return str.Substring(0, 1).ToUpper() + str.Substring(1);
108         }
109     }
110 }

运行结果如下:

 1 //我是设置示例代码
 2 HeroData heroData = new HeroData();
 3 heroData.setName("LiLei");
 4 heroData.setAge(18);
 5 heroData.setSkill(SkillData.datas[0]);
 6 heroData.PlaySkill();
 7 
 8 //我是不应该被替换的
 9 skillInfo.name = "DaJueZhao";
10 
11 //我是读取的示例代码
12 string name = heroData.getName();
13 int age = heroData.getAge();
14 Debug.Log("Name: " + name + ", Age: " + age);