Python Regular Expression Operations – Regex – POFTUT

Python Regular Expression Operations – Regex

Regular expression is popular topic in system administrators and developers. Regular expression is used to find structured text or string in single or multiple files. The best side of regular expression we can define whatever we want to match string in texts. Python supports and provides a lot of methods for regular expressions and related operations. In this tutorial we will look these regex functions in detail.

Import Re or Regular Expression Library

In order to work with regular expressions in python we need to import regular expression library which is named as shortcut of regular expression as regex .


Match function is one of the most popular function which will apply regex pattern into given string. We will use match function with pattern and string parameters. There is also flags parameter which can be used to provide some flags like case, interpretation etc. If we do not provide flags there will be no error.

In this example we want to find words which is delimited by spaces in given string. Each word provide single match and those matches will be grouped.


In previous part we have simply printed first group which index is   but we may have more than one word to match in a line. It is called group in regex. We can match multiple different patterns in a single match.

LEARN MORE  How To Add User To A Group In Linux

In this example we will match words starts with T and a into two groups.



As we see matched pattern results are assigned into groups. We can get them by providing index about these groups.


Search is similar to the match function but the main difference is match looks up to first match and then stops but search will look at to the end of string and will find multiple matches if exists. The syntax of the search function is the same match functions.,STRING,FLAG)

Search and Replace

Python regex functions supports finding given text and replacing the text with new one. We will use sub functions in order to replace. sub function supports following syntax.

We will change regular word with unregular word in this example.

Search and Replace

Search and Replace

Option Flags

Options flags generally provided as last parameter to the related regex functions. Option flags generally used to case-insensitive match, interpret with current locale etc. Here is a list of option flags.

  • re.I is used case-insensitive match
  • re.L is used for current locale
  • re.M makes $ match end of line
  • re.S makes . match any character, including newline
LEARN MORE  PowerShell Split String Operation With Examples

Case Insensitive

We can use option flags in order to make case-insensitive match or search with regular expression. We will provide re.I as last arguments to the relevant function like below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)