Home > C# > Matching IP Address using the Regular Expression

Matching IP Address using the Regular Expression

This example demonstrates the quick and simple way to match correct IP address.

MatchesDemo.zip

ipOK

ipBad

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Windows.Forms;

 namespace MatchesDemo
 {
     public partial class IPValidate : Form
     {
         public IPValidate()
         {
             InitializeComponent();
         }

         private void btnValidate_Click(object sender, EventArgs e)
         {
             // MessageBox.Show(mtxtIPAddress.Text);

             // create a regex object
             Regex checkIP = new Regex (@"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");

             // create match
             Match matchIP = checkIP.Match(mtxtIPAddress.Text);

             if (checkIP.IsMatch(mtxtIPAddress.Text))
             {
                 mtxtIPAddress.ForeColor = Color.Green;
             }
             else
                 mtxtIPAddress.ForeColor = Color.Red;
         }
     }
 }
Categories: C# Tags:
  1. No comments yet.
  1. No trackbacks yet.

Spam Protection by WP-SpamFree