DD
DevDash

Regex for Leading/Trailing Whitespace

Regex Pattern

^\s+|\s+$

Matches whitespace at the start or end (for trimming)

Quick Answer

The regex pattern for leading/trailing whitespace is `^\s+|\s+$`. Matches whitespace at the start or end (for trimming). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
leading✓ Matches
trailing ✓ Matches
both ✓ Matches
notrimming✗ No match
a b✗ No match

Code Examples

javascript

const regex = /^\s+|\s+$/;
const isValid = regex.test(value);

python

import re
pattern = r'^\s+|\s+$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^\s+|\s+$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^\s+|\s+$/', $value)) {
    echo "valid";
}

java

String pattern = "^\\s+|\\s+$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.