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.
- findall( )
- search( )
- split( )
- sub( )
- match( )
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)
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.
4. sub( ): - The sub( ) function replaces or substitutes the
matches with the text.
NOTE: - We can control the number of replacements by specifying
the count parameter.
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.
Example: -