C Addison Ritchie said:
This seems to work well.
using System.Text;
using System.Text.RegularExpressions;
// your string "112233445566";
string s = "112233445566";
// create the regular expression
Regex re = new Regex("(\\d\\d)");
// find the matches
MatchCollection matches = re.Matches();
// build the string
string result = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
matches[0].Value,
matches[1].Value,
matches[2].Value,
matches[3].Value,
matches[4].Value,
matches[5].Value);
return result;
The input string must be 12 characters long and all numbers. I would
assert that this is true before executing the above code.
That's terrible in terms of performance though - there's really no need
to use a regex here, IMO. Here's code which I believe would be
significantly faster:
if (s.Length != 12)
{
// Whatever your error handling is
}
foreach (char c in s)
{
if (c < '0' || c > '9')
{
// Whatever your error handling is
}
}
return String.Concat(s.Substring(0, 2), ":",
s.Substring(2, 2), ":",
s.Substring(4, 2), ":",
s.Substring(6, 2), ":",
s.Substring(8, 2), ":",
s.Substring(10, 2));
Alternatively, for the last bit:
char[] result = new char[17];
int resultIndex=0;
int origIndex=0;
for (int i=0; i < 6; i++)
{
result[resultIndex++]=s[origIndex++];
result[resultIndex++]=s[origIndex++];
if (i != 5)
{
result[resultIndex++]=':';
}
}
return new string(result);
(That avoids creating too many extra strings.)
I don't know which would be faster - or using a StringBuilder would be
better - but I don't think using a Regex here is a good idea.