简体   繁体   English

在 Python 中匹配八进制或十六进制表示的正确正则表达式是什么?

[英]What is the correct regex expression to match octal or hexadecimal representation in Python?

my current code is ^0x[az\d]+|^0o[\d]+ and it fails.我当前的代码是^0x[az\d]+|^0o[\d]+并且它失败了。

Capture numbers in octal or hexadecimal representation in Python.在 Python 中以八进制或十六进制表示形式捕获数字。 Octal numbers start with a prefix "0o" (number zero followed by lowercase letter o), and are followed by one or more numbers in the range of 0 to 7. Eg 0o112, 0o237, 0o07.八进制数字以前缀“0o”(数字 0 后跟小写字母 o)开头,后跟 0 到 7 范围内的一个或多个数字。例如 0o112、0o237、0o07。

Hexadecimal numbers start with a prefix "0x", and are followed by one or more numbers in the range of 0 to 9 or lowercase letters in the range of a to f.十六进制数字以前缀“0x”开头,后跟一个或多个 0 到 9 范围内的数字或 a 到 f 范围内的小写字母。 Eg 0xf3, 0x1d, 0x072.例如 0xf3、0x1d、0x072。

Use利用

 ^0(?:x[a-f0-7]+|o[0-7]+)$

EXPLANATION解释

-----------------------------------------------------------------------------
  ^                                  start of string
-----------------------------------------------------------------------------
  0                                  '0'
-----------------------------------------------------------------------------
  (?:x[a-f0-7]+|o[0-7]+)             'x' and one or more a-f / 0-7 characters
                                     or
                                     'o' and one or more 0-7 digits 
-----------------------------------------------------------------------------
  $                                  end of string    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM