1# Match first word of the string2re.findall("^\w+","His Phone isn't 578")
['His']
$ End of a String
1# Match last word of the string2re.findall("\w+$","His Phone isn't 578")
['578']
\b Word Boundary
1# Match all words starting with 'i' until non-space is found2re.findall(r"\bi\S+","His Phone isn't 578")
["isn't"]
\B Not a Word Boundary
1# Match all letters that are not at the beginning of a word 2# starting with 'i' until non-space is found3re.findall(r"\Bi\S+","His Phone isn't 578")
['is']
Quantifiers
? Zero or One
1re.findall("A-?B","AB A-B A--B A---B")
['AB', 'A-B']
* Zero or More
1re.findall("A-*B","AB A-B A--B A---B")
['AB', 'A-B', 'A--B', 'A---B']
+ One or More
1re.findall("A-+B","AB A-B A--B A---B")
['A-B', 'A--B', 'A---B']
{n} Exactly n
1re.findall("A-{2}B","AB A-B A--B A---B")
['A--B']
{m,n} Between m and n (inclusive)
1re.findall("A-{2,3}B","AB A-B A--B A---B")
['A--B', 'A---B']
Groups and Or
| OR Operator
1# OR operator2forxinre.finditer("(a|b)x","ax bx cx"):3print(x.group(0))
ax
bx
() Groups
1# the parentheses define groups2forxinre.finditer("is a (\w+) (\w+)","My vehicle is a red car, her vehicle is a blue bike"):3print(x.group(1)+" - "+x.group(2))
red - car
blue - bike
1# referencing groups in substitutions2# note that the entire pattern is being substituted but3# that specific components are selected in the substitution4re.sub("is a (\w+)\s(\w+)",r"is a \2 whose colour is \1","My vehicle is a red car, her vehicle is a blue bike")
'My vehicle is a car whose colour is red, her vehicle is a bike whose colour is blue'
(?:) Ignore Group
1# the first match is ignored. Only one group is returned2forxinre.finditer("is a (?:\w+) (\w+)","My vehicle is a red car, her vehicle is a blue bike"):3print(x.group(1))
car
bike
Labeled Groups
1# Iteration with labels2forxinre.finditer("(?P<name>Daisy)(?P<predicate>[\w ]*)(?P<dot>\.)","Daisy is a dachshund dog. Daisy is beautiful. She is 4."):3print(x.groupdict()['predicate'])
is a dachshund dog
is beautiful
Verbobe Mode (Useful with complex groups)
1# Use verbose mode 2text="""
323423\nDaisy is black, and beautiful. Taffy is brown, and short. \nOtto is cute, and happy."
4""" 5pattern="""
6(?P<name>\w*) # Alphanumerical word
7(\ is \ ) # followed by 'is'
8(?P<adj1>\w*) # followed by alphanumerical word
9(,\ and\ ) # followed by 'and'
10(?P<adj2>\w*) # followed by another alphanumerical word
11"""1213foriteminre.finditer(pattern,text,re.VERBOSE):14print(item.groupdict())
1# Look ahead helps create user-defined, non-consuming matches 2# 'ahead' of the expression, like '$'3re.findall(r"\w+(?=[,!]\s?)","One, two, three!")
['One', 'two', 'three']
(?<=) Look Behind
1# Look behind helps create user-defined non-consuming matches 2# 'behind' of the expression, like '^'3re.findall("(?<=[Uu]n)\w+","Undo it! It was unintentional!")
['do', 'intentional']
Look Ahead and Behind
1# Both look ahead and look behind can be combined2re.findall("(?<=<tag>).+(?=</tag>)","<tag>hello world</tag>")