Loading lesson path
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.
Formula
Python has a built - in package called re, which can be used to work withRegular Expressions.
import re
When you have imported the re module, you can start using regular expressions:
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)The re module offers a set of functions that allows us to search a string for a match:
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 are characters with a special meaning:
[]
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 » ^
"^hello" Try it » $
"planet$" Try it » *
"he.*o" Try it » +
"he.+o" Try it » ?
"he.?o" Try it »
{}"he.{2}o"Try it » |
"falls|stays" Try it » ()