in reply to Regular expression for hexadecimal number

Something like....

    /0x(?-i:[\da-f]{1,4})/

... should do the trick. Curlies are pretty slow, relatively speaking, though. You will achieve approximately equivalent results with

    /0x(?-i:[\da-f]+)/

except that this will also match "0xdeadbeefcafe" and the like (which might be considered a feature).

Note that you do not want to use, as suggested elsewhere in this thread:

    /0x[\da-f]{1,4}/i # or /0x[\da-f]+/i

...since that would allow 0X2a (note the uppercase X) which is not a legal hexadecimal definition.

• another intruder with the mooring in the heart of the Perl

Replies are listed 'Best First'.
Re^2: Regular expression for hexadecimal number
by amarquis (Curate) on Jul 30, 2007 at 14:54 UTC

    Hmm, this answers a question that's been in the back of my mind for a while, "Can you turn on/off modifiers in the middle of a regex."

    Thanks for prompting me to pop over to Perldoc to learn about it.

    A question, though: The goal is to keep the 0x case sensitive (to disallow 0X, as you said), but let the hex that follows match in a case insensitive way (i.e. match both 0xFF and 0xff)? If so, doesn't (?-i:PATTERN) actually turn off the insensitivity modifier (which wasn't on?). Based on my (probably wrong) interpretation of what I just learned at Perldoc, it seems like you'd want (?i:PATTERN) to turn it on.

      What you describe is accomplished not by using a modifier, but by being explicit in the definition of the char class:

      m/0x[\da-fA-F]{1,4}/;

      There's no reason to have or use modifiers on only part of a regex, when one can simply use the mechanisms already available to accomplish the same goal.

      <radiant.matrix>
      Ramblings and references
      The Code that can be seen is not the true Code
      I haven't found a problem yet that can't be solved by a well-placed trebuchet