C#Regex验证Mac地址

时间:2013-05-08 19:17:32

标签: c# regex

我正在尝试验证mac地址。在这种情况下,没有-:,例如有效的mac可能是:

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

但是,在针对以下代码运行时,我仍然会出现错误:

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();
        }
    }
}

输出:Mac无效

6 个答案:

答案 0 :(得分:10)

.NET regex 不支持POSIX字符类 。即使它确实支持,您需要将其括在[]中以使其生效,即[[:xdigit:]],否则,它将被视为具有字符:的字符类,{ {1}},xdig

您可能需要此正则表达式(在清除不需要的字符后对于MAC地址):

t

请注意,通过清理空格字符串^[a-fA-F0-9]{12}$ -,您将允许输入如下所示:

:

DEMO

答案 1 :(得分:5)

请尝试使用此正则表达式:

^(?:[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}$

匹配

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

但不是:

  • 12:34-4556-67

编辑:您的代码适合我。

enter image description here

答案 2 :(得分:1)

好像你可以这样做:

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}))$");

或者这个,这更简单,更宽容一点:

Regex r = new Regex("^([0-9a-fA-F]{2}(?:[:-]?[0-9a-fA-F]{2}){5})$");

答案 3 :(得分:0)

我会使用像这样的正则表达式,我自己:

Regex rxMacAddress = new Regex( @"^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((:[0-9a-fA-F]{2}){5}))$") ;

6对十六进制数字,分隔符用冒号或连字符,但不是混合符。

答案 4 :(得分:0)

你的正则表达并不好。在这里你得到了一个好的:

public const string ValidatorInvalidMacAddress = "^([0-9A-Fa-f]{2}[:-]?){5}([0-9A-Fa-f]{2})$";

答案 5 :(得分:0)

对我有用的正确正则表达式,并接受带有all-或all:分隔符的macaddress是:-“ ^ [0-9a-fA-F] {2}((((:: [0-9a-fA- F] {2}){5})|((-[0-9a-fA-F] {2}){5}))$“