Python Regular Expression Cheat Sheet



flags when compiling: Mac pages templates free download.

The Python RegEx Cheat Sheet for Budding Programmers Get Creative When Using Python Learning Python's regular expressions is a big step towards becoming a better Python programmer, but that's just one of the few things you need to do. However, playing around with its syntaxes and getting creative with them polishes your coding skill. This cheat sheet is based on Python 3’s documentation on regular expressions. If you’re interested in learning Python, we have a free Python Programming: Beginner course for you to try out. Download the cheat sheet here. Special Characters ^ Matches the expression to its right at the start of a string. It matches every such instance.

(All images PD, released by author, LionKimbro.)

Searching & Matching

You can search or match.

  • search -- find something anywhere in the string, and return it

  • match -- find something from the beginning of the string, and return it

You can also split on a pattern.

For example:

..which produces:

Compiling

If you use a regex a lot, compile it first.

Consider:

..which outputs: ('h1', 'robot', 'h1')

If you were going to do that match a lot, you could compile it, like so:

Cheat

.. Apple malware removal. which yields the same result.

The relative speed of compiled versus non-compiled patterns can be shown using the timeit module:

The above numbers were produced on an Intel Core i7 3770k running Python 2.7.6 (circa 2014). You should run the above commands on your Python version and specific hardware, and use patterns that represent your problem domain, for more representative results.

See Also

  • 4.2 re module -- PythonLibraryReference

  • 4.2.1 Regular Expression Syntax -- PythonLibraryReference

  • Regular Expression HOWTO - excellent Python-based regular expression tutorial, by A.M. Kuchling.

  • Regex in a Nutshell cheat sheet

  • RegexBuddy - Handy tool to create and test Python regular expressions

  • Summary of Regular Expression Patterns -- by DavidMertz

  • redemo tool -- ships with Python (C:Python24ToolsScriptsredemo.py), indispensible when trying out regular expressions; ships with PythonCard as well

  • periodic table of PERL operators -- for those who like visualization

  • Regular Expression Starter -- A simple guide for beginners

  • SVG source: 1,2.

Discussion

Requests

  • documentation on using re with Unicode .?

Problem?

The following feature does not seems to work in python:

For example, the ICU regular expression provides the following patterns:

  • N{UNICODE CHARACTER NAME} Correspond au caractère nommé
  • p{UNICODE PROPERTY NAME} Correspond au carctère doté de la propriété Unicode spécifiée.
  • P{UNICODE PROPERTY NAME} Correspond au carctère non doté de la propriété Unicode spécifiée.
  • s Correspond à un caractère séparateur. un séparateur est définit comme [tnfrp{Z}].
  • uhhhh Correspond à un caractère dont la valeur hexa est hhhh.
  • Uhhhhhhhh Correspond à un caractère dont la valeur hexa est hhhhhhhh. Exactement huit chiffres héxa doivent être fournis, même si le code point unicode le plus grand est U0010ffff.

-- anonymous

I don't understand the problem. -- LionKimbro 2006-03-25 16:31:35

Visualization

Python Regex Special Characters List

  • I like the Venn diagram in this image. However, one part of the image is confusing. Where it refers to python strings, and 'regex strings' (which are actually Python 'raw' strings) and something called 'match strings' .. what are these 'match strings. -- JimD 2004-12-30 20:03:54

The image isn't meant to be explanatory, it is meant to be reference and refreshing material.

That said: The 'match string' is the final product of either of the two above expressions. It is what the above two expressions will literally match. If you have a better phrase, or would like to correct 'raw' to 'regex,' feel free to download the SVG, edit the text, place an image on the web, and link it from here. (The damn LongImageIncorporationProcess strikes again.) I may eventually get around to it myself one day, but it seems there are higher priorities, and the diagram is 'good enough.'

That said, I appreciate the correction. -- LionKimbro 2005-01-01 00:22:14

Image Hosting

At the top of this page were two images/scehmes about re. Is it possible to redraw them here somehow? That server is not working, maybe someone has them dowloaded locally. Thanks a lot. -- PavelKosina

I've uploaded one as an attachment, still need to upload the other.. And, the source..

Python Regular Expression Cheat Sheet Pdf

(Anyone can do this, though, when the computers are online.)

Expressions

Regular Expression Pdf

-- LionKimbro 2006-03-25 16:31:35

Regex Cheat Sheet Pdf

CategoryDocumentation

Regular Expression Tester


Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ..
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ..
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ..
Flask app with Apache WSGI on Ubuntu14/CentOS7 ..
Selenium WebDriver
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ..
RabbitMQ(Message broker server) and Celery(Task queue) ..
OpenCV3 and Matplotlib ..
Simple tool - Concatenating slides using FFmpeg ..
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ..
Django 1.6/1.8 Web Framework ..