【问题标题】:Regular expression for hexadecimal and some other strings十六进制和其他一些字符串的正则表达式
【发布时间】:2012-12-06 12:42:39
【问题描述】:

我的目标是读取一个字符串,并在哪里找到整数或十六进制数,将其替换为“[0-9]” 我的字符串是:

a = hello word 123 with the 0x54673ef75e1a
a1 = hello word 123 with the 0xf
a2 = hello word 123 with the 0xea21f
a3 = hello word 123 with the 0xfa

尝试过以下方法:

b = re.sub(r"(\d+[A-Fa-f]*\d+[A-Fa-f]*)|(\d+)","[0-9]",a)

得到以下输出:

hello word [0-9] with the [0-9]x[0-9]a
hello word [0-9] with the [0-9]xf
hello word [0-9] with the [0-9]xea[0-9]
hello word [0-9] with the [0-9]xfa

但是输出应该是这样的:

hello word [0-9] with the [0-9]
hello word [0-9] with the [0-9]
hello word [0-9] with the [0-9]
hello word [0-9] with the [0-9]

【问题讨论】:

  • 尝试使用r'(0x[A-Fa-f\d]+|\d+)' 作为正则表达式。

标签: python regex python-2.6


【解决方案1】:

使用

re.sub(r"(0x[\da-fA-F]+)|(\d+)","[0-9]",a)

http://ideone.com/nMMNJm

【讨论】:

  • @DioF \d 处理小数。
  • 对……现在是凌晨。
【解决方案2】:

你的模式应该是这样的

b = re.sub(r"(0x[a-fA-F0-9]+|\d+)","[0-9]",a)

区分十六进制和十进制值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2019-04-25
    相关资源
    最近更新 更多