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
.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
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:
But not:
Edit: Your code works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With