C.W.K.
Stream
Lesson 11 of 12 · published

Negation vs Anchor — When ^ Means What

~6 min · caret, context, common-bug

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

Two completely different meanings of ^

The caret has TWO meanings depending on context. This trips up everybody at some point.

  • Outside a character class: ^ is the start-of-string anchor.
  • Inside a character class, as the first character: ^ negates the class.
  • Inside a character class, NOT as the first character: ^ is literal.

So ^[abc] means "start of string, then an a, b, or c."

And [^abc] means "any character that's not a, b, or c."

And [a^b] means "a, literal caret, or b."

The bug class this creates

The most common bug: writing ^[abc] when you meant [^abc]. The first matches "a/b/c at the start of the string" — only matches one character. The second matches "anything except a/b/c" — anywhere.

When debugging a pattern that's behaving wrong, look at every ^ and ask: "Am I inside or outside square brackets? And is it position 1?"

The same is true for $ — but less confusing

$ has only one meaning (end-of-line/string). It's never special inside a character class. [a$b] is just "a, dollar sign, or b." No surprise.

Code

Caret context bugs·python
import re

# Anchor — start of string
re.findall(r'^[abc]', 'apple banana')
# ['a']  — only 'a' at start; 'b' in 'banana' is NOT at start

# Negated class — anywhere
re.findall(r'[^abc]', 'apple banana')
# ['p', 'p', 'l', 'e', ' ', 'n', 'n', 'n']  — every non-abc character

# Literal caret — inside class but not first
re.findall(r'[a^b]', 'a^b^a')
# ['a', '^', 'b', '^', 'a']

External links

Exercise

Predict the output of these three patterns against 'cat dog fish': (a) r'^[cdf]', (b) r'[^cdf]', (c) r'[c^df]'. Write your prediction down BEFORE running them. Score yourself.

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.