简体   繁体   中英

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.

Capture numbers in octal or hexadecimal representation in 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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