crazydev
crazydev

Reputation: 575

Extract MAC address from a string

I have a string like this : 00:1E:AE:4F:20:0BDntl3l

I want to extract the mac address that is 00:1E:AE:4F:20:0B from the string using a regex and discard the Dntl3l. How can I achieve this in c# ?

I have tried the below code, but its still returning me the same string.

    string s = "00:1E:AE:4F:20:0BDntl3l";
    var regex = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
    var newformat = Regex.Match(s, regex);
    Console.WriteLine(newformat);

Upvotes: 1

Views: 1345

Answers (1)

Seva
Seva

Reputation: 1739

The following worked for me:

var s = "DSz00:1E:AE:4F:20:0BDntl3l";

var macRegex = "([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}";
var result = Regex.Match(s, macRegex);

Console.WriteLine(result); // 00:1E:AE:4F:20:0B

But I personally find this a bit confusing, so I would do something like this instead:

var s = "DSz00:1E:AE:4F:20:0BDntl3l";

var hexPair = "[0-9A-Fa-f]{2}";
var macRegex = $"{hexPair}:{hexPair}:{hexPair}:{hexPair}:{hexPair}:{hexPair}";
var result = Regex.Match(s, macRegex);

Console.WriteLine(result); // 00:1E:AE:4F:20:0B

Edit: Or, if you combine the two:

var s = "DSz00:1E:AE:4F:20:0BDntl3l";

var hexPair = "[0-9A-Fa-f]{2}";
var macRegex = $"({hexPair}:){{5}}{hexPair}";
var result = Regex.Match(s, macRegex);

Console.WriteLine(result); // 00:1E:AE:4F:20:0B

Edit 2: Yet another one I came up with using Enumerable.Repeat from LINQ and String.Join(), although I think this is an overkill :

var s = "DSz00:1E:AE:4F:20:0BDntl3l";    

// Make an IEnumerable of 6 hex pair regexes
var sixHexPairs = Enumerable.Repeat("[0-9A-Fa-f]{2}", 6);

// And join them with a ":"
var macRegex = string.Join(":", sixHexPairs);
var result = Regex.Match(s, macRegex);

Console.WriteLine(result); // 00:1E:AE:4F:20:0B

Upvotes: 7

Related Questions