Tutorial 2: Regular Expressions in Python —Using regex metacharacters \w, \s, \d
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
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 !!!