user60465
user60465

Reputation: 39

Hex string validation error

I was trying to validate 32 hexadecimal characters string using regular expression:

^[0-9A-Fa-f]+$

however, wrong strings like

123456789012345678901234567890gg

or

1234567890123456789012345678gggg

were accepted. What can be the reason?

Upvotes: 0

Views: 57

Answers (2)

walid toumi
walid toumi

Reputation: 2272

Use a

\A[A-Fa-f0-9]{32}\z

For all engine not support \z and \A anchors you can use instead:

^[a-fA-F0-9]{32}$

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Just use a lookahead in your regex to allow only 32 characters,

^(?=.{32}$)[0-9A-Fa-f]+$

DEMO

^[0-9A-Fa-f]+$ allows one or more hexadecimal character. To limit the characters, you need to specify the character limit within a lookahead (?=...) or within set brackets {}.

Upvotes: 0

Related Questions