用十进制表示替换所有十六进制数字 [英] Replacing all Hex numbers with Decimal representation

查看:147
本文介绍了用十进制表示替换所有十六进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串: string s =我最喜欢的数字是:42,0x42,24和0x24

有没有一种方法可以使用正则表达式将所有十六进制数字替换为它们的十进制表示形式?



对于上面的例子,我期望得到:我最喜欢的数字是:42,66,24和36正则表达式和转换 ):

  String source =我最喜欢的号码是:42,0x42,24和0x24; 

String result = Regex.Replace(source,@0x(\d | [af] | [AF])+,
(MatchEvaluator)(match => Convert。 ToInt32(match.Value,16).ToString()));

我假定所有的十六进制数字都是非负数足够小 int


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.

这篇关于用十进制表示替换所有十六进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆