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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.