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

Category: Strings

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:

Rate This Regex
Sending
User Review
0 (0 votes)

Expression Flags

Flags Description
i Ignore case sensitive.
g Allows global search.
m Allows multiline search.