首页 > 应用开发 > IT综合 > C#中利用正则表达式实现字符串搜索之一
| Regex r; // 声明一个 Regex类的变量 r = new Regex("s2000"); // 定义表达式 |
| Regex r = new Regex("abc"); // 定义一个Regex对象实例 Match m = r.Match("123abc456"); // 在字符串中匹配 if (m.Success) { Console.WriteLine("Found match at position " + m.Index); //输入匹配字符的位置 } |
| MatchCollection mc; String[] results = new String[20]; int[] matchposition = new int[20]; Regex r = new Regex("abc"); //定义一个Regex对象实例 mc = r.Matches("123abc4abcd"); for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配 { results[i] = mc[i].Value; //将匹配的字符串添在字符串数组中 matchposition[i] = mc[i].Index; //记录匹配字符的位置 } |
| using System; using System.Text.RegularExpressions; public class RegexTest { public static void RunTest() { Regex r = new Regex("(a(b))c"); //定义组 Match m = r.Match("abdabc"); Console.WriteLine("Number of groups found = " + m.Groups.Count); } public static void Main() { RunTest(); } } |
| Number of groups found = 3 |
| using System; using System.Text.RegularExpressions; public class RegexTest { public static void RunTest() { int counter; Match m; CaptureCollection cc; GroupCollection gc; Regex r = new Regex("(Abc)+"); //查找"Abc" m = r.Match("XYZAbcAbcAbcXYZAbcAb"); //设定要查找的字符串 gc = m.Groups; //输出查找组的数目 Console.WriteLine("Captured groups = " + gc.Count.ToString()); // Loop through each group. for (int i=0; i < gc.Count; i++) //查找每一个组 { cc = gc[i].Captures; counter = cc.Count; Console.WriteLine("Captures count = " + counter.ToString()); for (int ii = 0; ii < counter; ii++) { // Print capture and position. Console.WriteLine(cc[ii] + " Starts at character " + cc[ii].Index); //输入捕获位置 } } } public static void Main() { RunTest(); } } |
| Captured groups = 2 Captures count = 1 AbcAbcAbc Starts at character 3 Captures count = 3 Abc Starts at character 3 Abc Starts at character 6 Abc Starts at character 9 |
| Regex r; Match m; CaptureCollection cc; int posn, length; r = new Regex("(abc)*"); m = r.Match("bcabcabc"); for (int i=0; m.Groups[i].Value != ""; i++) { cc = m.Groups[i].Captures; for (int j = 0; j < cc.Count; j++) { posn = cc[j].Index; //捕获对象位置 length = cc[j].Length; //捕获对象长度 } } |
![]() 图1:对象关系 |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8781179/viewspace-920003/ ,如需转载,请注明出处,否则将追究法律责任。