string YourString = "sdafsdfdf192.168.1.1sdfdf234.123.234.234dafsd34.543.334.3dfasd2.23.4asdfsdf32.234.234.234.345.345asdfsdf";MatchCollection mc = Regex.Matches( YourString, @"(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])" );
foreach( Match ip in mc ) { Console.WriteLine( ip.Value.ToString() ); }
string ss = "" ;要赋值的字符串 string s = "C>* 192.168.5.5/30 is directly connected, eth1/7.200C>* 10.0.2.16/29 is directly connected, eth1/10.201C>* 58.216.219.32/29 is directly connected, eth1/13.114C>* 58.216.246.136/29 is directly connected, eth1/13.110C>* 61.132.89.16/30 is directly connected, eth1/8.118C>* 61.132.89.24/29 is directly connected, eth1/9.111C>* 61.132.89.48/28 is directly connected, eth1/8.114C>* "; //要匹配的字符串Regex digitregex = new Regex(@"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$"); //刚才给的正规表达式MatchCollection mc = digitregex.Matches(s); if ( mc.Count > 0 ) { foreach (Match m in mc) { ss = m.Value ; } } 为什么mc.count都是0啊,根本没有匹配的,大家看看怎么回事
string IPstr="192.168.1.1";
string[] IP=IPstr.Split('.');
//之后IP就为: IP[0]="192",IP[1]="168".....
你需要转换为数字就来个Convert.TO...就OK了
foreach( Match ip in mc )
{
Console.WriteLine( ip.Value.ToString() );
}
string s = "C>* 192.168.5.5/30 is directly connected, eth1/7.200C>* 10.0.2.16/29 is directly connected, eth1/10.201C>* 58.216.219.32/29 is directly connected, eth1/13.114C>* 58.216.246.136/29 is directly connected, eth1/13.110C>* 61.132.89.16/30 is directly connected, eth1/8.118C>* 61.132.89.24/29 is directly connected, eth1/9.111C>* 61.132.89.48/28 is directly connected, eth1/8.114C>* "; //要匹配的字符串Regex digitregex = new Regex(@"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$"); //刚才给的正规表达式MatchCollection mc = digitregex.Matches(s);
if ( mc.Count > 0 )
{
foreach (Match m in mc)
{
ss = m.Value ;
}
}
为什么mc.count都是0啊,根本没有匹配的,大家看看怎么回事
因为其中第一个 ^ 和 最后一个 $ 表示这个字符串必须是一行的开始和结束。 换句话说,这个是只测试 "123.123.123.123" 是不是ip地址, 前后面都不能有其他字符串的.这个正则是网上验证是否ip地址的例子,要改一下,去掉那2字符就行了。