Regular Expressions: Hex Codes
Welcome to the Hex Codes lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Computers internally store text as numbers. As a shorthand, we usually write those numbers out as hexadecimal codes.
>
/\x41/.test('A'); // 'A' is x41Result:
true
For example, capital letter "A" has the hex code
x41. Regular expressions and most programming languages allow this "x" syntax. To match "A" in a regex, we can write\x41.>
/\x41/.test('an apple');Result:
false
>
/\x41/.test('CATS ARE GOOD');Result:
true
x42is "B".>
/\x42/.test('An apple');Result:
false
>
/\x42/.test('Both apples');Result:
true
Each digit can be a number, or a letter between "a" and "f". For example, "M" is
x4din hex. (Thexisn't a hex digit; it's telling us that this is a hex code.)>
/\x4d/.test('M');Result:
true
There's a hex code for each character, even ones that aren't letters. "?" is
x3fand "!" isx21.>
/\x3f/.test('?');Result:
true
>
/\x21/.test('!');Result:
true
We can use hex codes to match symbols that you may not be able to type.
The letter "ø" doesn't appear on an US-English keyboard. To match that letter, we can use its hex code
\xf8.>
/\xf8/.test('søt katt');Result:
true
If we have a keyboard that can type "ø", we can put it directly in a regex.
>
/ø/.test('smørbrød');Result:
true
Be careful: the syntax
\xcan only be followed by exactly two digits. Anything after the two digits will be a different part of the regex.>
/\x41d/.test('A');Result:
false
>
/\x5Ad/.test('Zd'); // "Z" is x5AResult:
true
If we write an
\xwith only one digit, it's no longer a character code. Instead, the\xmatches literal "x" characters.>
/\x4/.test('x4'); // This is probably a mistake with \x!Result:
true
Hexadecimal digits can be any character from 0-9, a-f, or A-F. If we use the wrong characters, the
\xwill match literal "x" again.>
/\xfg/.test('xfg');Result:
true