Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate hexadecimal string using regular expression

Tags:

regex

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?

like image 792
user1216216 Avatar asked Aug 09 '12 06:08

user1216216


People also ask

How do you validate expressions in regex?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.


2 Answers

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]+$'.

like image 169
Yuushi Avatar answered Sep 21 '22 15:09

Yuushi


^[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> 
like image 32
Preet Kukreti Avatar answered Sep 17 '22 15:09

Preet Kukreti