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.
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. Thislinedonotcontainsanyspaceortab.
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
$ egrep "\s" example.txt
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
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
<?php $text="This is a space delimited line."; $pattern="\s"; preg_match($pattern,$text,$mathes); print_r($mathes); ?>
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.
#!/bin/python import re text="This is a space delimited line." re.match(r'\s',text)
/\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);