Regex Space, Whitespace, Tab Usage Examples

When dealing with the text files such as log files, user list, server list etc we can use regex for formally structured files. Space, white-space, and tab are popular separating elements used in regex or CSV files. In this tutorial, we will examine how to use regex with space, whitespace, tab or no space, no whitespace and no tab.

Example Text

We will use the following text as an example.

This is a test text.
We     will provide different lines.
For example this sentence contains spaces and tabs.

Regex Space or Whitespace

The regular expression is expressed as \s in the regex language. We can use single or multiple \s without a problem. We will use egrep command which is used to run regular expressions on given text or file. In this example, we will search for spaces in the file named example.txt

$ egrep "\s" example.txt
Regex Space or Whitespace
Regex Space or Whitespace

Regex Ignore Space or Whitespace

If we want to skip the space or whitespace in the given text we will use -v before the \S. In this example, we will only print the lines that do not contain any space.

$ egrep -v "\S" example.txt
Regex Ignore Space or Whitespace
Regex Ignore Space or Whitespace

Regex Tab

The tab is a whitespace character which contains multiple spaces. We can maths those contains tabs with the \t like below.


Regex Space In PHP

PHP provides all features of the regular expressions. We can math lines that contain spaces with the preg_match() function like below. We will put matches to the $mathes variable and print with the print_r() function.


$text="This is a space delimited line.";





Regex Space In Python

Python language provides the match() function from re module. We can use \s with python in order to match spaces like below.


import re

text="This is a space delimited line."


Regex Space In JavaScript

Javascript also provides regex functionality to match spaces in the text. We can use /\s/g in order to match spaces with the regular expression.

var str="This is a space delimited line";

var mathes=/\s/g.exec(str);

LEARN MORE  Awk Regular Expression Commands and Examples

Leave a Comment