I have a string: string s ="My Favorite numbers are: 42, 0x42, 24 and 0x24"
Is there a way using Regex to replace all hex numbers to their Decimal representation?
For the example above, I would expect to get: "My Favorite numbers are: 42, 66, 24 and 36"
.
Try this (regular expression and conversion):
String source = "My Favorite numbers are: 42, 0x42, 24 and 0x24";
String result = Regex.Replace(source, @"0x(\d|[a-f]|[A-F])+",
(MatchEvaluator) (match => Convert.ToInt32(match.Value, 16).ToString()));
I've assumed that all the hex numbers are non-negative and small enough to be int
.