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 https://docs.python.org/3/library/re.html .

You also obtain regular expression patterns from this site, http://www.regxlib.com .

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 ch16_01.py, and write these scripts.

import re

# pattern for numbers

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

print(p.match('19023'))

print(p.match('0000'))

print(p.match('12.789'))

print(p.match('12b23'))

# search

message = 'Anna William <anna@email.com>'

match = re.search(r'[\w.-]+@[\w.-]+', message)

if match:

    print(match.group())

# search and replase

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

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

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

print(resutl)

Save and run the program.

$ python3 ch16_01.py

Program output:

p16-1