扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
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:对象关系 |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者