How To Match Space In Regex?

Regex or Regular Expression is used to match specific patterns in different strings. It is very useful to detect patterns in a bunch of text or strings. Different characters are expressed with different regex signs. The space or whitespace can be also expressed in regex. The \s is used to express a single space, whitespace, tab, carriage return, new line vertical tab, and form feed characters in Regex. It can be used with other regex expressions in different ways.

  • A space character
  • A tab character
  • A carriage return character
  • A new line character
  • A vertical tab character
  • A form feed character

Match Space Regex

The \s is used to express space in regex. It can be used in different parts of a regex. In the following example, we create the regex which matches the words “wisetut” which starts with a space.

\swisetut
Match Space Regex

Match Tab Character

The \s can be used to match tab characters in a string. In the following example “I am wisetut” contains tabs and we match the “wisetut” which starts with tabs.

Match Tab Carriage Return or New Line Character

Newline or Carriage Return characters are also expressed as space characters and can be matched with the \s like below.

Match Tab Carriage Return or New Line Character

Do Not Match Space

We can also use the \s in order to not match spaces in a text. In the following example, we do not match or negate words those does not start with space.

^\s

Leave a Comment