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

来源:互联网 发布:淘宝cf抽奖怎么弄的 编辑:程序博客网 时间:2024/05/04 23:04

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

//定义要分解的字符串

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";

}

原创粉丝点击