您的位置:首页 > 其它

正则表达式提取练习2

2012-08-15 18:06 169 查看
using System;
using System.Collections.Generic;
using
System.Linq;
using System.Text;
using
System.Text.RegularExpressions;

namespace 正则表达式提取练习
{
class
Program
{
static void Main(string[] args)

{
#region 从路径中提取文件名

//string str =
@"c:\a\a\a\a\a\a\a\a.sql\a.sql\a.sql\a.sql\b.txt";

////这种思路不合适。
////Match match = Regex.Match(str,
@"\\\w+\.\w+");

////Console.WriteLine(match.Value);

//Match match =
Regex.Match(str,
@"^[a-zA-Z]:(\\\w+\.*\w*)+\\(.+)$");//写一个正则表达式与文件路径完全匹配。然后提取组

//if (match.Success)
//{
//
Console.WriteLine(match.Groups[2].Value);
//}

//Console.ReadKey();

#endregion

#region 从“June 26 ,
1951”中提取出月份June来。@"([a-zA-Z]+)\s+\d{1,2},\s*\d{4}"进行匹配。

//string str = "June 26 , 1951";

////通过提取组的方式,将所要的数据提取出来

//Match match = Regex.Match(str,
@"^([a-zA-Z]+)\s*(\d{1,2})\s*,\s*(\d{4})$");

//if
(match.Success)
//{
//
Console.WriteLine(match.Groups[1].Value);
//
Console.WriteLine(match.Groups[2].Value);
//
Console.WriteLine(match.Groups[3].Value);
//}

//Console.ReadKey();

#endregion

#region
“192.168.10.5[port=21,type=ftp]”,这个字符串表示IP地址为192.168.10.5的服务器的21端口提供的是ftp服务,其中如果“,type=ftp”部分被省略,则默认为http服务。请用程序解析此字符串,然后打印出“IP地址为***的服务器的***端口提供的服务为***”

////192.168.10.5[port=21]

//// string msg =
"192.168.10.5[port=21,type=ftp]";
//string msg =
"192.168.10.5[port=21]";
////[0-9]
//Match match =
Regex.Match(msg,
@"^((\d{1,3}\.){3}\d{1,3})\[port=(\d+)(,type=([a-zA-Z]+))?\]$");

//if (match.Success)
//{
//
Console.WriteLine("ip:{0}", match.Groups[1].Value);
//
Console.WriteLine("port:{0}", match.Groups[3].Value);
//
Console.WriteLine("services:{0}", (match.Groups[5].Value.Length == 0) ? "http" :
match.Groups[5].Value);
//}

//Console.ReadKey();
#endregion
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: