Convert hex representation inside a string to binary equivalent
In 开发者_开发知识库a string, replace every occurrence of <0xYZ> with the character of hex value YZ. The < and > characters will be used only for that purpose, the string is guaranteed to be well formatted.
Example ('0' = 0x30): A<0x30>B
=> A0B
It's an easy task, but there are many solutions and I was wondering about the best way to do it.
I think that a regular expression replace is the easiest way:
s = Regex.Replace(
s,
@"<0[Xx]([\dA-Fa-f]{2})>",
m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString()
);
By matching an exact pattern it places less restrictions on the string, for example that the <
and >
characters can still be used. Also, if a tag would happen to be malfomed, it will simply be left unchaged instead of causing an exception.
This will replace tags like <0X4A>
and <0x4a>
, but leave for example <0x04a>
unchanged.
You can easily do it with a regular expression:
s = Regex.Replace(s, "<0x([0-9a-f]+)>",
m => Char.ConvertFromUtf32(
Int32.Parse(m.Groups[1].Value, NumberStyles.HexNumber))
);
It is probably missing a few error checks. This uses an overload of Regex.Replace
that takes a MatchEvaluator
.
Match the number and convert to int then to char.
var str = "A<0x30>B";
var result = Regex.Replace(str, "<0x((\\d|[A-Z])+)>",
delegate (Match m)
{
return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
}, RegexOptions.IgnoreCase);
Output
A0B
精彩评论