Appendix E

Regular Expressions

E.0 Introduction

Often you need to write the code to validate user input such as to check whether the input is a number, a string with all lowercase letters, or a social security number. How do you write this type of code? A simple and effective way to accomplish this task is to use the regular expression.

A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. Regular expression is a powerful tool for string manipulations. You can use regular expressions for matching, replacing, and splitting strings.

E.1 Getting Started

To use regex, import the re module. You can use the split function in the module to split a string. For example,

splits ab bc cd into ...

Get Introduction to Python Programming and Data Structures, 3rd Edition by Pearson now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.