Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Validating Mac Address

Tags:

c#

regex

I am trying to validate mac addresses. In this instance there is no - or : for example a valid mac would be either:

0000000000
00-00-00-00-00-00
00:00:00:00:00:00

However I keep getting false when run against the below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace parsingxml
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Give me a mac address: ");

            string input = Console.ReadLine();
            input = input.Replace(" ", "").Replace(":","").Replace("-","");

            Regex r = new Regex("^([:xdigit:]){12}$");


            if (r.IsMatch(input))
            {
                Console.Write("Valid Mac");
            }
            else
            {
                Console.Write("Invalid Mac");
            }
            Console.Read();
        }
    }
}

OUTPUT: Invalid Mac

like image 252
Zac Borders Avatar asked May 08 '13 19:05

Zac Borders


2 Answers

.NET regex does not have support for POSIX character class. And even if it does support, you need to enclose it in [] to make it effective, i.e. [[:xdigit:]], otherwise, it will be treated as a character class with the characters :, x, d, i, g, t.

You probably want this regex instead (for the MAC address after you have cleaned up the unwanted characters):

^[a-fA-F0-9]{12}$

Note that by cleaning up the string of space, - and :, you will allow inputs as shown below to pass:

   34:   3-342-9fbc: 6:7

DEMO

like image 118
nhahtdh Avatar answered Sep 24 '22 06:09

nhahtdh


Try this regex instead:

^(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}|(?:[0-9a-fA-F]{2}-){5}[0-9a-fA-F]{2}|(?:[0-9a-fA-F]{2}){5}[0-9a-fA-F]{2}$

Matches:

  • 12-23-34-45-56-67
  • 12:23:34:45:56:67
  • 122334455667

But not:

  • 12:34-4556-67

Edit: Your code works for me.

enter image description here

like image 27
qJake Avatar answered Sep 22 '22 06:09

qJake