Python Regular Expressions - Python Programming by Example (2015)

Python Programming by Example (2015)

16. Python Regular Expressions

This chapter explains how to work with regular expressions in Python.

16.1 Getting Started

Regular expressions are a powerful language for matching text patterns. The Python "re" module provides regular expression support. This library can be read on .

You also obtain regular expression patterns from this site, .

16.2 Demo

In this demo, we create three scenario:

· Validate number data

· Search data

· Search and replace data

We can use match() from re object to validate the matching of defined pattern. To search, you can use search() function and use pub() to replace data.

Let's create a file, called, and write these scripts.

import re

# pattern for numbers

p = re.compile('^[0-9]+$')





# search

message = 'Anna William <>'

match ='[\w.-]+@[\w.-]+', message)

if match:


# search and replase

message = 'aaa : asasasw :: sasas:::'

p = re.compile('(:|::|:::)')

resutl = p.sub('<>', message)


Save and run the program.

$ python3

Program output: