Search code examples
regexpcre

Regular expression to capture hex numbers with odd number of characters


I have a list of comma separated hex numbers like below,

    aaffd,123,1,d3213,aaa,f
    aaa,dd,1234,d,c

And I want a regular expression for pcregrep to match only the lines containing hex numbers where each hex number has odd number of characters.

Should match:

    aaffd,123,1,d3213,aaa,f
    1
    2,345,1

Should not match:

    ad,ad
    1,23,1,333

I am trying with this regex ([0-9a-f],?|((?:(?:[0-9a-f]{2})+[0-9a-f]),?))+

But it captures unnecessary lines as well. As shown in the link https://regex101.com/r/uvJcbD/5

How to capture only the lines containing hex numbers where each hex number has odd number of characters? Thank you in advance.


Solution

  • This does the job:

    ^(?=[0-9a-f,]+$)[^,](?:[^,]{2})*(?:,[^,](?:[^,]{2})*)*$
    

    DEMO