Reputation: 29
How can I trim all valid mac addresses from multi vendor switch mac-address table dumps?
I've got the following so far...
string strLineBuf = "Cisco 10 001c.aabb.ccdd Gi0/50";
// string strLineBuf = "HP 001caa-bbccdd 50 10";
// string strLineBuf = "Other 00:1c:aa:bb:cc:dd 50";
// finds valid MAC addresses with space before and after
Regex rex = new Regex(@"^.* ([0-9A-F]{2}[:.-]?){5}[0-9A-F]{2} .*$", RegexOptions.IgnoreCase);
Match m = rex.Match(strLineBuf);
if (m.Success)
{
Console.WriteLine("Valid MAC found in line :)");
// trim MAC from line
// save line to arraylist
}
The input lines won't necessarily have the same number of chars before or after the MAC address. With an input file such as:
Cisco 10 001c.aabb.ccdd Gi0/50
HP 001caa-bbccdd 50 10
Other 00:1c:aa:bb:cc:dd 50
I'd like an output of:
Cisco 10 Gi0/50
HP 50 10
Other 50
Upvotes: 1
Views: 536
Reputation: 9041
You're pattern already matched your sample data, so I just tweaked to actually match the entire mac address into a capture group so that a String.Replace()
could be done to remove it.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
List<string> data = new List<string>()
{
"Cisco 10 001c.aabb.ccdd Gi0/50",
"HP 001caa-bbccdd 50 10",
"Other 00:1c:aa:bb:cc:dd 50"
};
foreach (string strLineBuf in data)
{
// Finds valid MAC addresses with space before and after
Regex rex = new Regex(@"^.* (([0-9A-F]{2}[:.-]?){5}[0-9A-F]{2}\s?).*$", RegexOptions.IgnoreCase);
Match m = rex.Match(strLineBuf);
if (m.Success)
{
Console.WriteLine(strLineBuf.Replace(m.Groups[1].Value, String.Empty));
}
}
}
}
Results:
Cisco 10 Gi0/50
HP 50 10
Other 50
Upvotes: 1
Reputation: 31656
You may have to tweak the Mac pattern but 12 minimum seemed reasonable hint to give to the parser to make it work.
var data = @"Cisco 10 001c.aabb.ccdd Gi0/50
HP 001caa-bbccdd 50 10
Other 00:1c:aa:bb:cc:dd 50";
var pattern =
@"^
(?<Brand>.+?)
(?:\s+)
(?<MAC>[\w.:\-]{12,})
(?:\s+)
(?<Data>[^\r\n]+)";
Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
.OfType<Match>()
.Select (mt => new
{
Brand = mt.Groups["Brand"].Value,
MAC = mt.Groups["MAC"].Value,
Data = mt.Groups["Data"].Value
}
)
Resultant Dynamic Entities
Upvotes: 1