Home > DeveloperSection > Forums > Is there a better way to format this string?
Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    December-12-2013 2:01 AM

 C# C# 
Ratings:


 1 Reply(s)
 870  View(s)
Rate this:

Is there a better way to format this string?

var Mac = sdr.GetString(0);

string trimMac = Mac.Replace("-", "");

string formatMac = trimMac.Insert(4, ".");

string formatAgain = formatMac.Insert(9, ".");

string dudeWTF = formatAgain.Trim();


Please help.


Pravesh Singh

Total Post:411

Points:2881
Posted on    December-12-2013 2:29 AM

Hi Manoj,

Why do something simple, when you can use a...

REGULAR EXPRESSION

private static readonly string _InnerPattern = "([a-zA-Z0-9]{2})";

private static readonly string _Pattern = string.Format("{0}-{0}-{0}-{0}-{0}-{0}", _InnerPattern);

private static readonly string _ReplacePattern = "$1$2.$3$4.$5$6";

private static readonly Regex _TransformRegex = new Regex(_Pattern, RegexOptions.Compiled);

public static string TransformMacAddressUsingRegex(string input)

{

    return _TransformRegex.Replace(input, _ReplacePattern);

}

The expression above creates a capture group for each set of characters separated by a hyphen "-", then constructs the output string using the contents of those capture groups.

Don't want to miss updates? Please click the below button!

Follow MindStick