最近經常用到正則,不過不同語言之間的正則一些特性差別比較大,自已寫個小工具,分享下:
下載地址:http://xiaoxiao.bfor.cn/download/regex.rar
按慣例,上幾張圖:
最後那個,生成代碼,使用RichTextBox對代碼着色分二步:
關鍵字着色:
//定義關鍵字 string[] keys = new string[] { "using", "return", "if", "else", "public" }; foreach (string key in keys) { Regex r = new Regex(key); MatchCollection mc = r.Matches(rtxtCode.Text); foreach (Match m in mc) { if (m.Success)//當匹配成功,對關鍵字着色 { rtxtCode.Select(m.Index, m.Length); rtxtCode.SelectionColor = Color.Blue; } } }
字符串着色這個要單獨來:
Regex r1 = new Regex("\"(?<string>[^\"]*)\""); MatchCollection mc1 = r1.Matches(rtxtCode.Text); foreach (Match m in mc1) { if (m.Success) { Group g = m.Groups["string"]; if (g.Success) { rtxtCode.Select(g.Index - 1, g.Length + 2); rtxtCode.SelectionColor = Color.Red; } } }
方法是查找字符串索引,右邊去掉一個字符,右邊加2,當然複雜的就不適用了,需要用環視判斷字符邊界,另外還要區分字符串中的轉義符..