EverythingPython

import re

I was writing some tests for work today and I accidentally ended up using the re.match() function instead of re.search() function and I thought I’d write that as today’s mini-TIL.

In a nutshell,

re.match() checks for a match only at the beginning of the string,

whereas

re.search() checks for a match anywhere in the string.

Here’s a quick example to illustrate the difference:

 1import re
 2
 3string = "Was it a car or a cat I saw?"
 4string2 = "Severus was impressed at Harry's Occlumency skills but he did not show it."
 5# re.match() will return None
 6print(re.match("cat", string))
 7
 8# re.search() will return a match object
 9print(re.search("cat", string))
10
11# re.match() will return a match object
12print(re.match("Severus", string2))
13
14# re.search() will return a match object
15print(re.search("Severus", string2))

Output -

1None
2<re.Match object; span=(18, 21), match='cat'>
3<re.Match object; span=(0, 7), match='Severus'>
4<re.Match object; span=(0, 7), match='Severus'>

Other regex functions that are worth reading about are -

Here’s an example using them all -

 1
 2import re
 3
 4string = "Was it a car or a cat I saw?"
 5string2 = "Hello, World!"
 6# re.match() will return None because the pattern does not match the beginning of the string
 7print(re.match("cat", string))
 8
 9# re.match() will return a match object with the first match - checking in string 2
10print(re.match("Hello", string2))
11
12
13# re.search() will return a match object with the first match
14print(re.search("cat", string))
15
16# re.findall() will return a list of all matches as strings
17print(re.findall("cat", string))
18
19# re.finditer() will return an iterator of all matches as match objects
20for match in re.finditer("cat", string):
21    print(match)
22
23# re.fullmatch() will return None because the pattern does not match the entire string
24print(re.fullmatch("cat", string))
25
26# re.split() will return a list of strings split by the pattern provided
27print(re.split(" ", string))
28
29# re.sub() will return a string with the substitution made
30print(re.sub("cat", "dog", string))

Output -

1None
2<re.Match object; span=(0, 5), match='Hello'>
3<re.Match object; span=(18, 21), match='cat'>
4['cat']
5<re.Match object; span=(18, 21), match='cat'>
6None
7['Was', 'it', 'a', 'car', 'or', 'a', 'cat', 'I', 'saw?']
8Was it a car or a dog I saw?