Portrait of Michael Limberger

Michael Limberger

Need me? Email mike@limberger.ca

Regex

Regex Fundamentals - The Building Blocks

The alphabet of regex

Before we touch any tools, learn the characters that have special meaning.

Letters match letters

Most characters match themselves. The pattern cat matches the text "cat". Simple.

Show me.

Pattern:  cat
Matches:  "The cat sat on the mat"
              ^^^

No magic here: letters match letters.

The dot is any one character

The dot . matches ANY single character. It is the wildcard.

Pattern:  c.t
Matches:  cat, cot, cut, c9t, c!t

Pattern:  h.t
Matches:  hat, hit, hot, hut, h@t

Pattern:  gr.y
Matches:  gray, grey

One dot equals one character. The dot does not care what that character is.

Square brackets pick from a list

A character class is square brackets: you list which characters are allowed.

Show me.

Pattern:  [aeiou]
Matches:  Any single vowel

Pattern:  gr[ae]y
Matches:  gray OR grey (not both at once)

Pattern:  [a-z]      Any lowercase letter
Pattern:  [A-Z]      Any uppercase letter
Pattern:  [0-9]      Any digit
Pattern:  [a-zA-Z]   Any letter
Pattern:  [a-zA-Z0-9]
Matches:  Any letter or digit

Pattern:  [^0-9]
Matches:  Anything that is NOT a digit

The caret ^ at the start of a character class means "not". A range uses a dash: [0-9].

Shorthand classes

Typing [0-9] gets old. These shortcuts exist:

Shorthand Means Same as
\d Any digit [0-9]
\D NOT a digit [^0-9]
\w Word character [a-zA-Z0-9_]
\W NOT a word character [^a-zA-Z0-9_]
\s Whitespace Space, tab, newline
\S NOT whitespace Anything except whitespace

Show me.

Pattern:  \d\d\d
Matches:  Any three digits (123, 456, 789)

Pattern:  \w+
Matches:  One or more word characters

Anchors are positions, not characters

^ is start of line. $ is end of line.

Pattern:  ^Hello
Matches:  "Hello world" but NOT "Say Hello"

Pattern:  world$
Matches:  "Hello world" but NOT "world peace"

Pattern:  ^Hello$
Matches:  Only a line containing exactly "Hello"

Anchors are crucial for precision. Without them, patterns match anywhere in the text.

Escape when you want the literal

Want an actual dot? Or a dollar sign? Use a backslash.

\.    Literal dot
\$    Literal dollar sign
\^    Literal caret
\[    Literal opening bracket
\\    Literal backslash

Pattern:  photo\.jpg
Matches:  "photo.jpg" (not "photoxjpg")

The special characters, named out loud

Glyph Job
. Any character
^ Start of line, or NOT inside [^...]
$ End of line
[ ] Character class
\ Escape
| OR (alternation)
( ) Grouping
* Zero or more
+ One or more
? Zero or one
{ } Specific count

When you want the literal character, escape it with a backslash.

Read these before you move on

Pattern Matches
a.c abc, aXc, a9c (any single char between a and c)
[abc] a, b, or c (just one)
[^abc] Anything except a, b, or c
\d Any single digit
^start "start" at beginning of line
end$ "end" at end of line
file\.txt Literally "file.txt"