Developer Toolbox

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.

Open in Regex Tester The pattern and every example below are filled in.

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+$/g

A 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 re as written. re.ASCII keeps \d to 0-9, as in JavaScript (Python matches any Unicode digit otherwise). Use re.fullmatch to 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 the D modifier, $ 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.ECMAScript keeps \d to 0-9, as in JavaScript. $ also matches before a final newline; to reject one, end the pattern with \z instead.

Common mistakes

  • Use the built-in trim

    s.trim() in JavaScript, s.strip() in Python and in Java 11 or later, and strings.TrimSpace in 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 replace stops after the first match: the leading run when there is one, otherwise the trailing run. Python's re.sub and PHP's preg_replace replace every match by default.

  • What counts as whitespace

    In JavaScript, \s includes 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.