regex anchors — ^ and $ match start and end
Quick Answer
// Match entire string
/^hello$/.test('hello') // true
/^hello$/.test('say hello') // false
/^hello$/.test('hello world') // false
# Python
import re
re.fullmatch(r'hello', 'hello') # matches
re.match(r'^hello$', 'hello') # matches
re.match(r'^hello$', 'hello world') # None
Usage
Without anchors, a pattern can match anywhere in the string. Use ^ and $ to constrain where the match occurs.
Other causes & fixes
Validate entire input
// JavaScript — validate hex color
/^#[0-9a-fA-F]{6}$/.test('#ff5733') // true
/^#[0-9a-fA-F]{6}$/.test('#ff5733xx') // false
# Python — validate US zip code
bool(re.fullmatch(r'\d{5}(-\d{4})?', '12345')) # True
bool(re.fullmatch(r'\d{5}(-\d{4})?', '12345-6789')) # True
\A and \Z — always match string boundaries (Python)
\A and \Z always match the start and end of the whole string, even with re.MULTILINE.
import re
text = "line1\nline2"
re.findall(r'^\w+', text, re.MULTILINE) # ['line1', 'line2'] — ^ per line
re.findall(r'\A\w+', text, re.MULTILINE) # ['line1'] — always string start
Multiline mode changes ^ and $ behavior
// In multiline mode, ^ and $ match per line
const lines = "first\nsecond\nthird";
lines.match(/^\w+$/gm) // ['first', 'second', 'third']
Related