I'm trying to parse a user-entered hex string so that I can emit a correctly formatted version to disk.
The "correct" format, in this case, looks like A1 F5 E1 C9
- space separated bytes with uppercase hex letters. However, the user input might not have spaces (A1F5E1C9
), might have line breaks (A1 F5\nE1 C9
), might have leading or trailing space (\nA1 F5 E1 C9\n\n\n
), and might have dashes instead of spaces (A1-F5-E1-C9
). It might have any combination of those variations, as well. Some of the numbers this will be used on are public keys, which can be quite long.
How can I handle reformatting this? The two semi-solutions I've been able to come up with so far are
BigInteger.Parse(value.Trim()
.Replace(" ", "")
.Replace(@"\n", "")
.Replace(@"\r", ""),
NumberStyles.HexNumber).ToString("X2");
which still doesn't produce a spaced-out string, or
string.Join(" ", Regex.Matches(a, @"([0-9A-Fa-f]{2})")
.Cast<Match>()
.Select(x => x.Captures[0].Value.ToUpper()))
which does work, but feels like it has a lot of extraneous overhead (Regex, LINQ).
Is the second method actually the best way to do this? Is there something obvious I'm overlooking?