Replacing all Hex numbers with Decimal representat

2019-08-08 16:01发布

问题:

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".

回答1:

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.