Reputation: 137
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
Upvotes: 5
Views: 18713
Reputation: 21
using System.Net.NetworkInformation;
try{
PhysicalAddress py = PhysicalAddress.Parse("abcd");
}catch(Exception){
Console.WriteLine("Mac address not valid");
}
Upvotes: 1
Reputation: 1
Correct Regex expression that worked for me and accept either macaddress with either all - or all : separation is :- "^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((-[0-9a-fA-F]{2}){5}))$"
Upvotes: 0
Reputation: 1
Your regex isn't good. Here you got a good one:
public const string ValidatorInvalidMacAddress = "^([0-9A-Fa-f]{2}[:-]?){5}([0-9A-Fa-f]{2})$";
Upvotes: 0
Reputation: 74297
I'd use a regular expression like this one, myself:
Regex rxMacAddress = new Regex( @"^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((:[0-9a-fA-F]{2}){5}))$") ;
6 pairs of hex digits, separator either by colons or by hyphens, but not a mixture.
Upvotes: 0
Reputation: 17139
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.
Upvotes: 5
Reputation: 149020
Seems like you could just do this:
Regex r = new Regex("^([0-9a-fA-F]{2}(?:(?:-[0-9a-fA-F]{2}){5}|(?::[0-9a-fA-F]{2}){5}|[0-9a-fA-F]{10}))$");
Or this, which is a lot simpler and would be a little more forgiving:
Regex r = new Regex("^([0-9a-fA-F]{2}(?:[:-]?[0-9a-fA-F]{2}){5})$");
Upvotes: 2
Reputation: 56819
.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
Upvotes: 10