Replacing all Hex numbers with Decimal representation

无人久伴 提交于 2019-12-11 10:54:38

问题


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.



来源:https://stackoverflow.com/questions/28274757/replacing-all-hex-numbers-with-decimal-representation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!