C.W.K.
Stream
Lesson 03 of 10 · published

Literal Matching: The 80% You Already Know

~8 min · literals, fundamentals

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Most of regex is just typing the letters you want

Beginners get scared by \b\w+@\w+\.\w+\b and forget that the simplest, most common regex is just… the literal string.

The pattern cat matches the substring cat. Anywhere it appears. cat in scatter, cat in concatenate, cat in cat. That's it. No magic, no special meaning. Most characters in regex are literal — they match themselves.

Which characters are NOT literal

A small set of characters have special meaning. They're called metacharacters. Memorize this list — it's the entire "why does my pattern do something weird?" troubleshooting guide:

.  ^  $  *  +  ?  (  )  [  ]  {  }  |  \

Every other character — letters, digits, spaces, hyphens (mostly), commas, colons — is literal. If you want a metacharacter to be literal, you put a backslash in front of it: \. matches a literal dot.

The implicit "contains"

By default, cat means "is the string cat somewhere inside the input?" not "is the entire input the string cat?" That's a critical distinction. To match the *whole* input, you anchor the pattern with ^ and $ (covered in the Classes track) — ^cat$ matches only the exact string cat.

Different tools default differently. grep and Python re.search() are "contains." Python re.fullmatch() and JavaScript form-validation regex are "whole string." When a pattern surprises you, this is the first thing to check.

Code

Literal vs special·python
import re

# Pure literal — works as you'd expect
re.findall(r'cat', 'concatenate scatter cat')
# ['cat', 'cat', 'cat']

# Dot is special — matches ANY character
re.findall(r'c.t', 'cat cot cut c@t cxt')
# ['cat', 'cot', 'cut', 'c@t', 'cxt']

# Escape with backslash to make it literal again
re.findall(r'c\.t', 'cat c.t cot')
# ['c.t']

External links

Exercise

Write the literal pattern that matches the string 3.14 and only 3.14 — both as a substring search (just 3.14-shaped) and as a fullmatch (anchored). Then test it in a regex playground; predict whether 3x14 and 3X14 should match each version before you click Run.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.