Regular Expressions in Python

What are regular expressions?

Regular expressions are required when there is a need to perform high level advanced pattern base search or match strings. Regular expressions itself is a programming language in itself. For working with these expressions a module by the name of ‘re’ is defined in python. While dealing with regular expressions we are going to import this module in our program. There are two important functions that you must know to work with regular expressions:
(1)match function
(2) search function

match function

In this tutorial we will deal with the ‘match’ function. The syntax for the same is given below;

Re.match(expression, str, flag)

As you can see, the function can take three parameters. The first one expression refers to the regular expression that you want to match.

‘str’ is the string on which the search operation is performed to match the pattern of the string on which the search is performed.

The match function has a flag parameter which can help in controlling the match operation.

Regular functions are compiled into pattern objects. These objects have access to some methods that can help with the searching part. Let’s first take a look at a simple example:

import re

str_obj = re.compile("hello")
match_obj = str_obj.match("hello world")
if match_obj == None:
    print("Match not found")
else:
    print("match found")
        

Download the code
Run the code

We will now work on other example that would use re object the way we have shown in the syntax, but before we go ahead with that you need to know how to create and expression for search. For this you should have Knowledge of Identifiers and modifiers.

Identifiers

\d stands for any number
\D stands for anything but number
\s space
\S stands for anything but space
\w stands for character
\W stands for anything but a character
. stands for any character except a new line
\b whitespace around words
\. Looking for a ‘.’

Modifiers

{} curly brackets define what we expect
+ look for one or more matches
? look for 0 or 1 match
* look for 0 or more matches
$ look for a match at the end of the string
^ look for a match at the beginning
| either or
[] defines range or variance

import re
match_obj = re.match(r'b[a-z]a','beautiful')
if(match_obj):
    print("Match found")
else:
 
   print("Match Not found")

Download the code
Run the code

Look at the expression: r’b[a-z]a’. Since we are dealing with raw strings the expression is written within r”. We are trying to find out if the word ‘beautiful’ starts with ‘b’ , ends with ‘a’ and has any other small letter from[a-z] range. If yes, then it is a match else not a match. ‘bea’ falls in this range hence the match os found. In the next tutorial we will look at the search function.

<<< GeneratorsRegular Expressions in Python – II >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .