将正则表达式模式应用于输入字符串所找到的成功匹配的集合
2015-12-22 12:55
281 查看
先定义正则表达式,
Regex itineraryRegex = new Regex(@"[\""][\s\w|\u4E00-\u9FA5a-zA-Z:.,-:]+[\""]");
string strline="字符串";
//将匹配出满足条件的集合,以迭代方式
MatchCollection itineraryMcc = itineraryRegex.Matches(strline);
for (int i = 0; i < itineraryMcc.Count; i++)
{
string strResline = itineraryMcc[i].Value.Trim();//获取每一个的值
}
集合是固定不变 (只读) 并且没有公共构造函数。 Regex.Matches 方法返回 MatchCollection 对象。
集合包含零个或多System.Text.RegularExpressions.Match对象。如果匹配成功,将该集合填充与其中一个System.Text.RegularExpressions.Match对于每个输入字符串中找到的匹配项的对象。如果匹 配不成功,则集合中不包含System.Text.RegularExpressions.Match对象,并将其Count属性相等,则为零。
将正则表达式模式应用于特定的输入字符串,正则表达式引擎使用两种技术之一来生成MatchCollection对象:
直接计算。
MatchCollection对象一次,填入到特定的调用导致的所有匹配项Regex.Matches方法。使用这一技术时的集合Count访问属性。它通常是填充集合的成本更高的方法,并需要更高的性能下降。
迟缓计算。
MatchCollection对象是否已填充根据需要在每个匹配的项。它等效于正则表达式引擎调用Regex.Match方法重复并将每个匹配项添加到集合。通过访问该集合时使用此方法,是其GetEnumerator方法中,或使用访问时foreach语句 (在 C#) 或For Each...Next语句 (在 Visual Basic 中)。
public static void Main () { // Define a regular expression for repeated words. Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); // Define a test string. string text = "The the quick brown fox fox jumped over the lazy dog dog."; // Find matches. MatchCollection matches = rx.Matches(text); // Report the number of matches found. Console.WriteLine("{0} matches found in:\n {1}", matches.Count, text); // Report on each match. foreach (Match match in matches) { GroupCollection groups = match.Groups; Console.WriteLine("'{0}' repeated at positions {1} and {2}", groups["word"].Value, groups[0].Index, groups[1].Index); } }
相关文章推荐
- python getopt.getopt 不能精确匹配的问题
- < %=request.getParameter(“username”)% > 等价于 ${ param.username }
- Brodatz纹理图像库
- js选项卡
- JMeter:Linux上安装&运行JMeter
- 代码校验工具 SublimeLinter 的安装与使用
- 理解矩阵(三)
- ViewPager onPageChangeListener总结
- 理解矩阵(二)
- 理解矩阵(一)
- 《RocketMq》四、Producer生产者
- NSUserDefaults存储数据
- c语言用宏模拟泛型容器
- Android中使用OkHttp框架
- 技术路线的选择重要但不具有决定性
- PMCAFF 八周年老友会倒计时 | 北京活动
- Android属性 android:focusableInTouchMode
- 快速掌握一个语言最常用的50%
- 代码之谜(五)- 浮点数(谁偷了你的精度?)
- (NO.00005)iOS实现炸弹人游戏(二):素材选择的取舍