PYTHON - REGEX
Say for example, you have saved a long paragraph in a file. And you want to search if a particular block of String is present in it or not.
Or maybe you have stored some data in a Collection(Say, List, Set e.t.c.).
Well! We have seen some ways of searching the data. But now, let us see a better one.
And as said, Regex provides a better searching experience with some pattern.
Python has a package named 're'. We need to import that and start working with Regex.
import re
Note : Don't get panicked by the below Functions. We will provide a detailed explanation for the below Functions, once we start learning the Regex patterns.
To work with 'Regex', we need a few methods that Regex package offers. They are :
-
findall( )
findall( ) Function returns the searched results as a List.
-
search( )
search( ) Function returns a Match Object if the pattern is matched.
-
split( )
split( ) Function returns the searched results as a List, splitted by the search pattern.
-
sub( )
sub( ) Function is used to replace the searched pattern with a given text.
-
subn( )
subn( ) Function is exactly similar to sub( ) Function with an added feature. i.e. The subn( ) Function returns a tuple that contains the replaced string and the number of times
the replacement is made.
In the next tutorial, let us look 'Regex' Patterns and see how the above Functions works.