Day 9

Pramod Ray
2 min readSep 18, 2019

--

Regular Expression: The regular expressions can be defined as the sequence of characters which are used to search for a pattern in a string. The module re provides the support to use regex in the python program. The re module throws an exception if there is some error while using the regular expression.

.     Matches with any single character except newline '\n'
? Match 0 or 1 occurrence of the pattern to its left
+ 1 or more occurrence of the pattern to its left
* 0 or more occurrence of the pattern to its left
\w Matches with a alphanumeric character
\W (upper case W) matches non-alphanumeric character.
\d Matches with digits[0-9]
\D (upper case D) matches with non-digits.
^and$ match the start or end of the string respectively.
\S (upper case S) matches any non-white space character.
\s Matches with a single white space character (space, newline, tab, form

Python has a module named re to work with RegEx:

The re module must be imported to use the regex functionalities in python.

Syntax:
import re
phone_number=re.compile(r'\w\d+')
matches=phone_number.search('My number is 8987399271')

1 match:This method matches the regex pattern in the string with the optional flag. It returns true if a match is found in the string otherwise it returns false.

2 search:This method returns the match object if there is a match found in the string.

3 findall: It returns a list that contains all the matches of a pattern in the string.

4 split: Returns a list in which the string has been split in each match.

5 subReplace: one or many matches in the string.

The findall() function

This method returns a list containing a list of all matches of a pattern within the string. It returns the patterns in the order they are found. If there are no matches, then an empty list is returned.

Ex:-
import
re
str = “How are you. How is everything”
matches = re.findall(“How”, str)
print(matches)
print(matches)

The match object

The match object contains the information about the search and the output. If there is no match found, the None object is returned.

Ex:-
import
re
str = “How are you. How is everything”
matches = re.search(“How”, str)
print(type(matches))
print(matches)

The Match object methods

There are the following methods associated with the Match object.

  1. string(): It returns a string passed into the function.
  2. group(): The part of the string is returned where the match is found.

--

--

Pramod Ray
Pramod Ray

No responses yet