Regular expression for a hexadecimal number greater than 10 and should be even in length

Rohit Pathak :

How do I create a regular expression that detects the hexadecimal numbers which have a length that meets the following requirements: even, greater than or equal to 10, and less than 256.

For example:

0x1234567890 Accepted
0x123456789 rejected
123456789 rejected
1234567890 accepted
12345678901 rejected
0x123456789012 accepted
123456789012 accepted

The regex:

^(0?[xX]?([^0-9a-fA-F]*(([0-9a-fA-F][0-9a-fA-F])+[^0-9a-fA-F]*)*))$

I have tried the above regex but it is not working as expected, it is checking for even length but not checking that if the input is greater than or equals to 10 or not.

here 0x or 0X is optional.. excluding that the length should be greater than or equals to 10

Wiktor Stribiżew :

You may use

^(?=.{10,255}$)(?:0x)?[0-9a-fA-F]{2}(?:[0-9a-fA-F]{2})*$

See the regex demo. Note that in Java, you may replace [0-9a-fA-F] with \p{XDigit}.

Details

  • ^ - start of string (implicit in matches)
  • (?=.{10,255}$) - from 10 to 255 chars must be up to the end of the string (here, the $ is obligatory)
  • (?:0x)? - an optional 0x char sequence
  • [0-9a-fA-F]{2} - two hex chars
  • (?:[0-9a-fA-F]{2})* - 0 or more sequences of double hex chars
  • $ - end of string (implicit in matches)

In Java, you may use it like

str.matches("(?=.{10,255}$)(?:0x)?[0-9a-fA-F]{2}(?:[0-9a-fA-F]{2})*")

Or

str.matches("(?=.{10,255}$)(?:0x)?\\p{XDigit}{2}(?:\\p{XDigit}{2})*")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325240&siteId=1