《C#编程之道》 之 使用正则表达式分解字符串

正则表达式在实际开发程序时经常用来处理一些数据格式,比如要使用正则表达式分解一个字符串,可以使用下面的代码:

//定义要分解的字符串

string str = "14:08:30 192.168.1.1 明日科技 14:08:40 192.168.0.1 编程词典 ";

//定义要按指定格式进行分解的正则表达式

Regex myRegex = new Regex(@"(?<time>(d|:)+)s" + @"(?<ip>(d|.)+)s" + @"(?<company>S+)s");

MatchCollection myMatches = myRegex.Matches(str);//对字符串按指定格式进行分解

foreach (Match myMatch in myMatches)//循环遍历分解后的字符串

{

    //输出表示time的字符串

    label1.Text += "n  时间:" + myMatch.Groups["time"].ToString();

    //输出表示ip的字符串

    label1.Text += "n  地址:" + myMatch.Groups["ip"].ToString();

    //输出表示company的字符串

    label1.Text += "n  公司:" + myMatch.Groups["company"].ToString() + "n";

}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值