sentence = "The toll-no is 800-123-2345 and 900-234-2345"
output = "800-123-2345"
I want to extract toll number which starts with the number 800.
sentence = "800-123-1243 and 900-345-6578 and 911-798-5768 and 900-1234-1234"
output = "".join([char for char in sentence if char.isdigit()])
print(output)
# output-
80012312439003456578911798576890012341234
CodePudding user response:
A non-regex way could use a simple list comprehension with string operations:
sentence = "800-123-1243 and 900-345-6578 and 911-798-5768 and 900-1234-1234"
out = [word for word in sentence.split()
if word.startswith('800') and word.replace('-', '').isdigit()]
Output: ['800-123-1243']
If you only want the first match (if any):
out = next((word for word in sentence.split()
if word.startswith('800') and word.replace('-', '').isdigit()),
None)
Output: '800-123-1243'
NB. the word.replace('-', '').isdigit()
is not strictly required with the provided example, but can help if the sentence is more complex and there is a risk of having words starting in 800
that are not phone numbers.
CodePudding user response:
If the pattern of the number is 800-NNN-NNNN, then you can find the first match using a simple regex:
import re
match = re.search(r'800-[0-9]{3}-[0-9]{4}', sentence)
result = match.group() if match else None