Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for hexadecimal

Tags:

python

regex

I have defined a regular expression of hexadecimal value of length 4 as follows:

([0-9A-F]{4})

And it works fine and grammatically

0000

is also a valid hexadecimal number , but I want to discard it from the valid matching and therefore looking forward to hint on how to extend the current regular expression so that

0000 is flagged as invalid and filtered out.

Thanks

like image 539
sajis997 Avatar asked Feb 03 '17 13:02

sajis997


People also ask

What is '?' In regular expression?

'?' matches/verifies the zero or single occurrence of the group preceding it. Check Mobile number example. Same goes with '*' . It will check zero or more occurrences of group preceding it.

What will the \$ regular expression match?

\$ will help to find the character "$" available in the content based on the expression flags assigned to the regular expression.

Is Hex valid?

Yes, in hexadecimal, things like A, B, C, D, E, and F are considered numbers, not letters. That means that 200 is a perfectly valid hexadecimal number just as much as 2FA is also a valid hex number.

What is the regular expression for characters?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.


1 Answers

You could use negative lookahead:

(?!0000)[0-9A-F]{4}

Here (?!0000) is a negative lookahead group. It more or less says: "And do not allow that the next elements are 0000" but without consuming them.

You can test it on regex101.

like image 180
Willem Van Onsem Avatar answered Oct 08 '22 15:10

Willem Van Onsem