Tutorial 2: Regular Expressions in Python —Using regex metacharacters \w, \s, \d

Gaurav Patil
3 min readSep 23, 2021

--

Photo by Ilya Pavlov on Unsplash

Missed previous tutorial ? — Click here

When I started learning coding , I found that concepts are better understood when used in variety of examples. That’s why I am giving many examples for each topic enlisted below. Click on the topic to navigate directly .

1. ‘\w’ (lower case) = Match any alphanumeric character

2. ‘\W’ (upper case) = Match any non-alphanumeric character

3. ‘\s’ (lower case) = Match any whitespace

4. ‘\S’ (upper case) = Match any non-whitespace character

5. ‘\d’ (lower case) = Match any digit

6. ‘\D’ (upper case) = Match any non-digit character

1. ‘\w’ (lower case) = Match any alphanumeric character

Alphanumeric character includes all upper case and lower case English alphabets along with digits 0–9 and underscore ‘_’

Let’s see how:

Consider a text is a message with one time password. We will extract alphanumeric characters from that message.

In the examples given below, we use two methods:

a) findall() method — It returns all the matches in the form of a list

b) sub() method — It returns a complete string after substituting a substring in a given text.

2. ‘\W’ (upper case) = Match any non-alphanumeric character

Using same two methods :

a) findall() method -

b) sub() method -

3. ‘\s’ (lower case) = Match any whitespace

Using same above two methods:

a) findall() method:

b) sub() method:

4. ‘\S’ (upper case) = Match any non-whitespace character

Using same two methods:

a) findall() method :

b) sub() method :

5. ‘\d’ (lower case) = Match any digit

Using same two methods:

a) findall() method :

b) sub() method :

6. ‘\D’ (upper case) = Match any non-digit character

Using same two methods :

a) findall() method :

b) sub() method :

You learnt six different characters and two different methods used in regex. I hope this was fun.

Congratulations !!

Take a deep breathe and move to the next tutorial.

Happy learning !!!

--

--

Gaurav Patil
Gaurav Patil

Written by Gaurav Patil

Machine Learning Engineer drawing insights from mathematics.

Responses (1)