正则表达式在实际开发程序时经常用来处理一些数据格式,比如要使用正则表达式分解一个字符串,可以使用下面的代码:
//定义要分解的字符串
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";
}
正则表达式解析示例
本文介绍了一种使用正则表达式从特定格式的字符串中提取数据的方法。通过一个具体的例子展示了如何定义正则表达式来匹配时间、IP地址和公司名称,并使用C#中的Regex类进行匹配。
389

被折叠的 条评论
为什么被折叠?



