正则表达式可以看做一种有特定功能的小型编程语言,在一段文本中定位子字符串。利用正则表达式可以快速地分析大量的文本以找到特定的字符模式;提取、编辑、替换或删除文本子字符串;或将提取的字符串添加到集合。正则表达式的基本语法可参见:深入浅出之正则表达式(一)深入浅出之正则表达式(二)

C#命名空间System.Text.RegularExpressions提供了支持正则表达式操作的类。这些类主要包括Regex,MatchCollection,Match,GroupCollection,Group,CaputerCollection和Caputer,下图表示了这些类之间的关系。

        public static void Main(string[] args)
{
string text = "I've found this amazing URL at http://www.sohu.com ,and then find ftp://ftp.sohu.com is better.";
string pattern = @"\b(\S+)://(\S+)\b"; //匹配URL的模式
MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合
Console.WriteLine("文本中包含的URL地址有:");
foreach (Match match in mc)
{
Console.WriteLine(match.ToString());
} Console.Read();
}
/*
* 运行后输出如下:
* 文本中包含的URL地址有:
* http://www.sohu.com
* ftp://ftp.sohu.com
*/

现在,要求变了,不仅要找出URL,还要找出每个URL的协议和域名地址,这时就要用到正则表达式的分组功能了。分组是要匹配的模式pattern用小括号括起来,分成不同的组,如可以把上面例子中的模式改为:string pattern = @"\b(?<protocol>\S+)://(?<address>\S+)\b"; 这样就用括号分成了两个组(实际上是三个组,因为匹配本身可以看做一个大组),"?<protocol>"和"?<address>"定义了每个组的别名protocol和address,这不是必须的,只是方便我们获取需要的组。示例代码如下

    public static void Main(string[] args)
{
string text = "I've found this amazing URL at http://www.sohu.com ,and then find ftp://ftp.sohu.com is better.";
string pattern = @"\b(?<protocol>\S+)://(?<address>\S+)\b"; //匹配URL的模式,并分组
MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合 Console.WriteLine("文本中包含的URL地址有:");
foreach (Match match in mc)
{
GroupCollection gc = match.Groups;
string outputText = "URL:" + match.Value + ";Protocol:" + gc["protocol"].Value + ";Address:" + gc["address"].Value;
Console.WriteLine(outputText);
} Console.Read();
}
/**
* 运行后输出如下:
* 文本中包含的URL地址有:
* URL:http://www.sohu.com;Protocol:http;Address:www.sohu.com
* URL:ftp://ftp.sohu.com;Protocol:ftp;Address:ftp.sohu.com
*/

最新文章

  1. Python下安装MySQLdb
  2. WLST 命令和变量
  3. Ubuntu环境下手动配置ElasticSearch0.90.5
  4. hdoj3351-stack
  5. Swift 添加到TableView实现动画效果
  6. ActiveMQ结合WebScoket应用例子以及介绍
  7. JavaScript八张思维导图—操作符
  8. 【ShoppingWebCrawler】-基于Webkit内核的爬虫蜘蛛引擎概述
  9. VS工具箱中添加DevExpress控件
  10. SAP 销售条件表增强栏位
  11. 【XSY1081】随机存储器 网络流
  12. 故障排错-ping dup!
  13. 几种序列化协议(protobuf,xstream,jackjson,jdk,hessian)相关数据对比
  14. 博文中标题的样式H1H2H3H4
  15. centos npm 安装后 command not found
  16. Struts2输入校验(编码方式)
  17. artDialog学习之旅(二)之扩展方法详解
  18. 从零開始学android&amp;lt;AnalogClock与DigitalClock时钟组件.三十一.&amp;gt;
  19. struts2:在Action中使用Servlet的API,设置、读取各种内置对象的属性
  20. numpy 基本使用1

热门文章

  1. Django分页器和自定义分页器
  2. PHP工厂模式demo
  3. Django中cookie&amp;session的实现
  4. CF数据结构练习
  5. H5 DeviceMotionEvent 事件制作“摇一摇效果”
  6. Highcharts 环境配置
  7. CRM 价格批导
  8. Java中获得当前静态类的类名
  9. Oracle 11.2.0.4.0 Dataguard部署和日常维护(4)-Datauard Gap事件解决篇
  10. vue-navigation 实现前进刷新,后退不刷新