Validate hexadecimal string using regular expression

I am validating a string whether it is hexadecimal or not using regular expression.

The expression I used is ^[A-Fa-f0-9]$. When I using this, the string AABB10 is recognized as a valid hexadecimal, but the string 10AABB is recognized as invalid.

How can I solve the problem?


Solution 1:

You most likely need a +, so regex = '^[a-fA-F0-9]+$'. However, I'd be careful to (perhaps) think about such things as an optional 0x at the beginning of the string, which would make it ^(0x|0X)?[a-fA-F0-9]+$'.

Solution 2:

^[A-Fa-f0-9]+$

should work, + matches 1 or more chars.

Using Python:

In [1]: import re

In [2]: re.match?
Type:       function
Base Class: <type 'function'>
String Form:<function match at 0x01D9DCF0>
Namespace:  Interactive
File:       python27\lib\re.py
Definition: re.match(pattern, string, flags=0)
Docstring:
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.

In [3]: re.match(r"^[A-Fa-f0-9]+$", "AABB10")
Out[3]: <_sre.SRE_Match at 0x3734c98>

In [4]: re.match(r"^[A-Fa-f0-9]+$", "10AABB")
Out[4]: <_sre.SRE_Match at 0x3734d08>

Ideally You might want something like ^(0[xX])?[A-Fa-f0-9]+$ so you can match against strings with the common 0x formatting like 0x1A2B3C4D

In [5]: re.match(r"^(0[xX])?[A-Fa-f0-9]+$", "0x1A2B3C4D")
Out[5]: <_sre.SRE_Match at 0x373c2e0>

Solution 3:

Do you forget the '+'? Trying "^[A-Fa-f0-9]+$"