Regex: Leading and trailing whitespace
Two alternatives joined by |: whitespace at the start of the string, or whitespace at the end. With the g flag, s.replace(/^\s+|\s+$/g, "") removes both runs and leaves the spaces inside the text alone.
Pattern
^\s+|\s+$ Flags: g
How it works
- ^\s+
- One or more whitespace characters at the start.
- |
- Or
- \s+$
- one or more at the end.
Matches
- padded
- padded
- both
- tabbed
Doesn't match
- no-padding
- inner space
- a
Matches: examples 1, 2, 3, 4 start or end with whitespace.
In your language
- JavaScript
/^\s+|\s+$/gA literal;
new RegExp(source, flags)builds the same from a string.- Python
re.compile(r"^\s+|\s+$", re.ASCII)A raw string, so backslashes reach
reas written.re.ASCIIkeeps\dto0-9, as in JavaScript (Python matches any Unicode digit otherwise). Usere.fullmatchto test a whole string.- Java
Pattern.compile("^\\s+|\\s+$")A normal string literal, so every backslash is doubled.
matcher(s).matches()tests the whole string.- Go
regexp.MustCompile(`^\s+|\s+$`)A raw string in backticks. RE2 runs in linear time but has no lookaround and no backreferences.
- PHP
preg_match('/^\s+|\s+$/D', $input)PCRE with
/delimiters inside a single-quoted string. Without theDmodifier,$also matches before a final newline, so it is added to patterns that end in$.- C#
new Regex(@"^\s+|\s+$", RegexOptions.ECMAScript)A verbatim string: backslashes stay, a quote is doubled.
RegexOptions.ECMAScriptkeeps\dto0-9, as in JavaScript.$also matches before a final newline; to reject one, end the pattern with\zinstead.
Common mistakes
Use the built-in trim
s.trim()in JavaScript,s.strip()in Python and in Java 11 or later, andstrings.TrimSpacein Go do this without a regex. The pattern is for tools that only offer find and replace.Without g, only the first match goes
Without the global flag, JavaScript's
replacestops after the first match: the leading run when there is one, otherwise the trailing run. Python'sre.suband PHP'spreg_replacereplace every match by default.What counts as whitespace
In JavaScript,
\sincludes the non-breaking space and the Unicode line separators; in Java and Go it is ASCII only. A non-breaking space pasted from a web page then survives in one language and not in another.