Basic replacement patterns
Replace all matches globally
"foo foo".replace(/foo/g, "bar")
Example:
sed -E "s/[0-9]{4}-[0-9]{2}-[0-9]{2}/DATE/g" file.txt
Case-insensitive replacement
text.replace(/error/gi, "WARN")
Example:
perl -pe "s/error/WARN/gi" app.log
Capture groups in replacement
Swap first and last name
"Ada Lovelace".replace(/(\w+) (\w+)/, "$2, $1")
Example:
sed -E "s/(.*),(.*)/\2-\1/" values.txt
Reformat date
"2026-02-01".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")
Example:
python -c "import re;print(re.sub(r"(\d{3})-(\d{2})-(\d{4})", r"***-**-\3", "123-45-6789"))"
Conditional and scoped replace
Replace at word boundaries only
text.replace(/\bcat\b/g, "dog")
Example:
text.replace(/\s+/g, " ").trim()
Replace only first occurrence
text.replace(/id=/, "ID=")
Example:
text.replace(/:/, " -> ")
Common mistakes / Pitfalls
- Forgetting global flag g replaces only the first match in many languages.
- Backreference syntax differs between tools ($1 vs \1), causing wrong output.
- Greedy capture groups can swallow too much text during replacement.
Last updated: February 2026