我有一个很长的字符串,里面有IP地址,我想把这些IP地址都取出来。
我找了一个正则表达式:
[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}
不知道对不对。
如果只是判断一个字符串是否匹配,我知道用Regex.IsMatch来判断,
请问:1.上面的正则表达式对不对?(不用判断IP的合法性)
2.可是如果我想实现我上面说的功能,把IP地址都找出来,该怎么做呢?

解决方案 »

  1.   

    static void Main(string[] args)
            {
                string strs = null;
                string str = "192.168.0.27fdsfs192.168.0.55";
                Regex r = new Regex(@"[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match m in r.Matches(str))
                {
                    foreach (Capture c in m.Captures)
                    {
                        strs += c.Value + "\r\n";
                    }
                }
                Console.WriteLine(strs); 
                Console.ReadLine();
            }
      

  2.   

                string str = @"";
                Regex reg = new Regex(@"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)");
                MatchCollection mc = reg.Matches(str);
                foreach (Match m in mc)
                {
                    Console.WriteLine(m.Groups[0].ToString());
                }
      

  3.   

    干嘛用正则自找麻烦呢。System.Net.IPAddress ip;
    if (System.Net.IPAddress.TryParse("192.168.0.2", out ip))
    {
        byte[] bzip = ip.GetAddressBytes();
        foreach (byte b in bzip)
        {
            MessageBox.Show(b.ToString());
        }
    }