Home > OS >  How to extract number after text which has "("
How to extract number after text which has "("

Time:07-16

import re
string = "He stay in office, you can call the Phone No : 987234567 or alternative number is Phone: (972) 590 5576 "
ref_no = re.findall(r"(?:(?<=Phone: )|(?<=Tel No: )|(?<=Phone No : ))[\d-] ",str(string))
print(ref_no)

Required solution 987234567, (972) 590 5576

Is there any solution to get number which has brackets

CodePudding user response:

import re
string = "He stay in office, you can call the Phone No : 987234567 or alternative number is Phone: (972) 590 5576 "
ref_no = re.findall(r"(?:(?<=Phone: )|(?<=Tel No: )|(?<=Phone No : ))(\(?\d{3}\)?[\s]?\d{3}[\s]?\d )",str(string))
print(ref_no)

output:
['987234567', '(972) 590 5576']

As the first phone number is having only 9 digits but not 10 in regular expression i have marked last pattern as \d which means it can have 1 or more occurrence of digits

CodePudding user response:

Well if there is only one parenthesis in the string as above, you can use substring to find whatever is inside the parenthesis.

string.find() method will return the index of the first occurrence of the specified character

Note that you don't need to use re with this solution!

string = "He stay in office, you can call the Phone No : 987234567 or alternative number is Phone: (972) 590 5576 "
num = string[string.find("(")   1 : string.find(")")]

Output:

972

  • Related