What is a regex and how does it actually work
pattern matching, regex engine, literal characters, match vs search, test method, basic syntax
Regex Is a Pattern Description Language
A regular expression is a string that describes a search pattern. You give the engine a pattern and a target string; it scans the string and tells you whether — and where — the pattern appears.
In most languages, regex runs on an engine built into the runtime. JavaScript uses a backtracking NFA engine. Python uses the re module. The syntax is 95% identical across both.
Your First Pattern
A sequence of literal characters matches exactly those characters, in that order.
// JavaScript
const pattern = /cat/;
console.log(pattern.test('the cat sat')); // true
console.log(pattern.test('concatenate')); // true — 'cat' is inside
console.log(pattern.test('CAT')); // false — case-sensitive by default
# Python
import re
print(bool(re.search(r'cat', 'the cat sat'))) # True
test() vs match() vs search()
test() returns a boolean — use it when you only need to know if a match exists. match() anchors at the start; search() scans the full string. For most validation tasks, test() is all you need. The regex engine reads left to right, attempts the pattern at each position, and stops at the first success.
The regex engine does not care about meaning — it only cares about structure. It scans left to right, position by position, trying to match the pattern at each index. If it fails, it advances one character and tries again. This makes regex both powerful and predictable: the same input always produces the same result. Understanding this scanning model is the foundation for everything else in this course, including why greedy quantifiers over-match and why anchors matter for validation.
