Python program to extract phone number from string using sub() method

Here, we will see a Python program to extract phone number from string using sub() method.
Submitted by Shivang Yadav, on March 10, 2021

The regular expression in Python is a search pattern formed by a sequence of characters.

The sub() method is used to replace all occurrences of a pattern in the string with a substring/character. There is an upper limit to replacing characters.

The method returns a string that contains characters after replacing the character. The method is included in the re library.

Syntax:

regular.sub(regularExp, replaceChar, string, UL)

Let's take an example to understand the problem,

Input:
string = "Your mobile number is : 9988-214-631"

Output:
9988214631

Program to illustrate the working of our solution

import re

myString = "Your mobile number is : 9988-214-631"
print("String\t: ",myString)

convNum = re.sub(r'\D' , "" , myString)
print("Phone\t: " , convNum)

Output:

String  :  Your mobile number is : 9988-214-631
Phone   :  9988214631

Python Regular Expression Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.