Regex To Match A String With No Whitespace At The Beginning And End

We encounter this problem all the time — needing to check if a string has whitespaces at the beginning and end. A simple solution is to use this regular expression, which allows you to validate a string with no whitespace at the beginning and end.

/^[^\s]+(\s+[^\s]+)*$/

Matches:

  • abcdef
  • 123456
  • a1b1c1d1

Non-matches:

  • <whitespace>abcdef
  • abcdef<whitespace>
  • <whitespace>abcdef<whitespace>

See Also:

Regex Is Copied!