簡體   English   中英

C# 正則表達式驗證 Mac 地址

[英]C# Regex Validating Mac Address

我正在嘗試驗證 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

.NET 正則表達式不支持 POSIX 字符類 並且即使支持,也需要將其括在[]中才能生效,即[[:xdigit:]] ,否則將被視為帶有字符的字符類: , x , d , i , gt

您可能需要這個正則表達式(清除不需要的字符后的 MAC 地址):

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

請注意,通過清理空格字符串-: ,您將允許如下所示的輸入通過:

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

演示

試試這個正則表達式:

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

編輯:您的代碼對我有用。

在此處輸入圖像描述

似乎你可以這樣做:

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

我自己會使用這樣的正則表達式:

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

6 對十六進制數字,用冒號或連字符分隔,但不能混合使用。

你的正則表達式不好。 在這里你有一個很好的:

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

正確的正則表達式對我有用,並接受帶有 all - 或 all 的 macaddress :分隔符是:- "^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{ 2}){5})|((-[0-9a-fA-F]{2}){5}))$"

        using System.Net.NetworkInformation;
        try{
            PhysicalAddress py = PhysicalAddress.Parse("abcd");
        }catch(Exception){
            Console.WriteLine("Mac address not valid");
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM