Title: Regular Expression By Example
Slug: regex_by_example
Summary: Regular Expression By Example
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
This tutorial is based on: http://www.tutorialspoint.com/python/python_reg_expressions.htm
In [1]:
# Import regex
import re
In [2]:
# Create some data
text = 'A flock of 120 quick brown foxes jumped over 30 lazy brown, bears.'
In [3]:
re.findall('^A', text)
Out[3]:
In [4]:
re.findall('bears.$', text)
Out[4]:
In [5]:
re.findall('f..es', text)
Out[5]:
In [6]:
# Find all vowels
re.findall('[aeiou]', text)
Out[6]:
In [7]:
# Find all characters that are not lower-case vowels
re.findall('[^aeiou]', text)
Out[7]:
In [8]:
re.findall('a|A', text)
Out[8]:
In [9]:
# Find any instance of 'fox'
re.findall('(foxes)', text)
Out[9]:
In [10]:
# Break up string into five character blocks
re.findall('\w\w\w\w\w', text)
Out[10]:
In [11]:
re.findall('\W\W', text)
Out[11]:
In [12]:
re.findall('\s', text)
Out[12]:
In [13]:
re.findall('\S\S', text)
Out[13]:
In [14]:
re.findall('\d\d\d', text)
Out[14]:
In [15]:
re.findall('\D\D\D\D\D', text)
Out[15]:
In [16]:
re.findall('\AA', text)
Out[16]:
In [17]:
re.findall('bears.\Z', text)
Out[17]:
In [19]:
re.findall('\b[foxes]', text)
Out[19]:
In [20]:
re.findall('\n', text)
Out[20]:
In [21]:
re.findall('[Ff]oxes', 'foxes Foxes Doxes')
Out[21]:
In [22]:
re.findall('[Ff]oxes', 'foxes Foxes Doxes')
Out[22]:
In [23]:
re.findall('[a-z]', 'foxes Foxes')
Out[23]:
In [24]:
re.findall('[A-Z]', 'foxes Foxes')
Out[24]:
In [25]:
re.findall('[a-zA-Z0-9]', 'foxes Foxes')
Out[25]:
In [26]:
re.findall('[^aeiou]', 'foxes Foxes')
Out[26]:
In [27]:
re.findall('[^0-9]', 'foxes Foxes')
Out[27]:
In [28]:
re.findall('foxes?', 'foxes Foxes')
Out[28]:
In [29]:
re.findall('ox*', 'foxes Foxes')
Out[29]:
In [30]:
re.findall('ox+', 'foxes Foxes')
Out[30]:
In [31]:
re.findall('\d{3}', text)
Out[31]:
In [32]:
re.findall('\d{2,}', text)
Out[32]:
In [33]:
re.findall('\d{2,3}', text)
Out[33]:
In [34]:
re.findall('^A', text)
Out[34]:
In [35]:
re.findall('bears.$', text)
Out[35]:
In [36]:
re.findall('\AA', text)
Out[36]:
In [37]:
re.findall('bears.\Z', text)
Out[37]:
In [38]:
re.findall('bears(?=.)', text)
Out[38]:
In [39]:
re.findall('foxes(?!!)', 'foxes foxes!')
Out[39]:
In [40]:
re.findall('foxes|foxes!', 'foxes foxes!')
Out[40]:
In [41]:
re.findall('fox(es!)', 'foxes foxes!')
Out[41]:
In [42]:
re.findall('foxes(!)', 'foxes foxes!')
Out[42]: