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

Negated Classes [^abc] — Everything Except

~6 min · negation, character-class

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

Caret as the first character means 'not'

[^abc] matches any single character that is NOT a, b, or c. The caret ^ at the start of a class flips the meaning — it's now "any character except these."

This is genuinely one of the most useful tools in regex. "Match until you hit a quote" → [^"]*. "Skip everything that's not a digit" → [^0-9]+. "Take all non-whitespace" → [^\s]+ (or just \S+, lesson 7).

Negated classes match newlines (unlike .)

This is the gotcha. [^x] matches every character that isn't x, INCLUDING \n. The dot . stops at newlines without DOTALL; negated classes don't. So [^"]* will happily span multiple lines, while .* won't.

This is sometimes what you want, sometimes not. If you're parsing a quoted string that legitimately spans lines, [^"]* is correct. If you want "everything until a quote on the same line," use [^"\n]*.

The caret is only special in position 1

[a^b] is the literal class "a, caret, or b." Caret is only the negation operator when it's the very first character inside the brackets.

Code

Negated classes pattern·python
import re

# Match a quoted string body (between quotes)
re.findall(r'"([^"]*)"', 'name="Pippa" age="3"')
# ['Pippa', '3']

# Match anything that ISN'T whitespace
re.findall(r'[^\s]+', 'hello world\tand\nfoo')
# ['hello', 'world', 'and', 'foo']

# Negated class spans newlines
re.findall(r'[^x]+', 'abc\ndef\nxyz')
# ['abc\ndef\n']  — \n was happily included

# Caret in position 2+ is literal
re.findall(r'[a^b]', 'a^b^a')
# ['a', '^', 'b', '^', 'a']

External links

Exercise

Write a pattern that captures the body of a <code>...</code> HTML tag using a negated class. Then write the same with .*?. Run both against <code>x</code> and <code>y</code> and notice which one matches what you want and why.

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.