Regular Expressions

Flashcard 1 of 10

Hexadecimal is the base 16 number system. It is typically written using all the base 10 numerals, as well as the letters "a" through "f".

We want to write a pattern to match all hexadecimal characters. As a start, we have the following pattern:

hex_pattern = \
  /^(0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f)+$/

# Valid matches
"123abd" =~ hex_pattern #=> 0
"456789" =~ hex_pattern #=> 0

# Invalid, not hex characters
"876jkl" =~ hex_pattern #=> nil

While the pattern does seem to work, it is a bit long and verbose. Is there any way we can simplify the pattern?

Sure! We can use [character classes][]:

hex_pattern = /^[0-9a-f]+$/

The character class is identical to the fully-specified pipe-separated list above, but it uses a character class and two character ranges to concisely express the pattern.

Note: Ruby's regex engine actually has a "metacharacter", \h, that matches any hex digit. Ruby's regex game is strong!

[character classes]: http://ruby-doc.org/core-2.1.1/Regexp.html#class-Regexp-label-Character+Classes [hexadecimal]: https://en.wikipedia.org/wiki/Hexadecimal

Return to Flashcard Results