Cheatsheet Pages / Regex Cheatsheet

How to trim leading and trailing whitespace with regex

User input arrives padded with spaces and you want the clean middle.

Patterns use the syntax shared by PCRE / Python / JavaScript; engine differences are flagged in the cheatsheet where they matter. Test any pattern at regex101.com — and pick the matching engine.

^\s+|\s+$
# replace matches with "" → "  hi  " becomes "hi"

Good to know

Used with a replace-by-empty-string: padded input comes back trimmed.

Regex Cheatsheet one-page card — patterns that actually work
The full one-page card — Regex Cheatsheet. Get the complete cheatsheet on GitHub