Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Regular expressions in python
  5. Matching vs. Searching

Matching vs. Searching

Search function searches the whole string to match the substring and returns its index.

syntax:-

re.search(substring, string, flag)>

e.g.,

import re
a="Python"
s=''' One of the most famous programming language in the world is Python.'''
print(re.search(a, s))

This is all about search function in python.

Match function attempts to match RE pattern to string with optional flags.

syntax:-

re.match(pattern, string, flags=0)

e.g.,

import re
a="Python"
s='''Python is one of the most popular programming languages in the world.'''
print(re.match(a, s, re.IGNORECASE))

This is all about match function in python.

Both return the first match of a substring found in the string, but re.match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none.
While re.search() searches for the whole string even if the string contains multi-lines and tries to find a match of the substring in all the lines of string.

e.g.,

import re
a="Python"
s=''' One of the most famous programming language in the world is Python.'''
print(re.search(a, s, re.IGNORECASE))
Print(re.match(a, s, re.IGNORECASE))

This is all about matching vs. searching in python.

Was this article helpful to you? Yes 3 No 3

How can we help?