bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Python/Foundations
Python•Foundations

Python RegEx

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.

RegEx Module

Formula

Python has a built - in package called re, which can be used to work with

Regular Expressions.

Import the re module:

import re

RegEx in Python

When you have imported the re module, you can start using regular expressions:

Example

Search the string to see if it starts with "The" and ends with "Spain": import re txt = "The rain in Spain"

Formula

x = re.search("^The.*Spain$", txt)

RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:

Function

Description findall

Returns a list containing all matches search

Returns a

Match object if there is a match anywhere in the string split Returns a list where the string has been split at each match sub Replaces one or many matches with a string

Metacharacters

Metacharacters are characters with a special meaning:

Character

Description

Example

Try it

[]

A set of characters

Formula

"[a - m]"

Try it » \ Signals a special sequence (can also be used to escape special characters) "\d" Try it ». Any character (except newline character) "he..o" Try it » ^

Starts with

"^hello" Try it » $

Ends with

"planet$" Try it » *

Zero or more occurrences

"he.*o" Try it » +

One or more occurrences

"he.+o" Try it » ?

Zero or one occurrences

"he.?o" Try it »

{}

Exactly the specified number of occurrences

"he.{2}o"

Try it » |

Either or

"falls|stays" Try it » ()

Capture and group

Previous

Python JSON

Next

Python PIP