Regular Expressions and methods

 Introduction of Regular Expressions: -

  • A Regular Expression (RegEx) is a sequence of characters that defines a search pattern to find, match, search, and manipulate a string or set of strings.
  • Python provides a built-in module called re, which is used to work with regular expressions.
  • To install module, use   py -m pip install regex
  • To import the module, use    import re
  • The re module offers a set of functions that allows us to search a string for a match.

  1. findall( )
  2. search( )
  3. split( )
  4. sub( )
  5. match( )

 1. findall( ): - The findall function returns a list containing all matches.

                         syntax: -  re.findall( pattern , string )

     Example: -                                                                                    


    Output: -


 

2. search( ): - The search function searches the string for a match and returns a match object if there is a match. If there is more then one match, only 1st occurrence of the match will be returned. If there is no match, None will ne returned.

                    syntax: -  re.search(pattern, string)

 Example: -                                                                                    


 

  Output: -       


NOTE: - The start( ) function locates the position of any character in a string.

    Output: -


3. split( ): - The split( ) function returns a list where the string has been split at each match.

                         syntax: -  re.split(pattern, string, maxsplit=0)

     Example: -                                                                                    


         Output: -    


4. sub( ): - The sub( ) function replaces or substitutes the matches with the text.

                     syntax: -  re.sub(pattern, replace, string, count=0)

         Example: -                                                                                     


          Output: -   


NOTE: - We can control the number of replacements by specifying the count parameter.


             output: -   


5. match( ): - The match( ) function checks if the pattern matches only at the beginning of the string. Returns a None value in the case of no match found.

                         syntax: -  re.match(string , pattern)

               Example: -                                                                                    

             Output: -



Popular posts from this blog

operators in c programming

Variables in c

Cloud Storage and Local Storage: Applications in Business