Regular expressions are also called regex. They are text matching patterns and have a formal syntax. The regular expression Python module “re” will be used.

>>> import re

Pattern searching

Let’s start off by searching for patterns in text.

>>> patterns = ['python', 'fun']

>>> sent = 'This is a sentence which says python is easy'

To search, “re.search()” is used where the first argument is what to search and the second one is from where to search.

So below we try searching “is” in “python is fun” and get the match.

>>> re.search('is', 'python is fun')
<re.Match object; span=(7, 9), match='is'>

Using this we will search for the pattern.

>>> for pattern in patterns:
        print('Searching for "{}" in: \n"{}"'.format(pattern, sent))

        if re.search(pattern,sent):
            print("\nPattern found\n")
        else:
            print("\nPattern not found\n")
Searching for "python" in: 
"This is a sentence which says python is easy"
Pattern found
Searching for "fun" in: 
"This is a sentence which says python is easy"
Pattern not found

Now let’s get a closer look at this match object.

>>> match = re.search(patterns[0], sent)

>>> type(match)
re.Match

This match object has its own methods which can be called. start() tells the index of the start of the match. end() tells index of the end of the match.

Image for post

match.start()
30

match.end()
36

#coding #programming #regex #python3 #python

Regular expressions in Python
1.35 GEEK