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

Viewed 59

my current code is ^0x[a-z\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. E.g. 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. E.g. 0xf3, 0x1d, 0x072.

1 Answers

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    
Related