Apple Interview Question
Staff EngineersCountry: United States
A simple regex of the form \(?\d{3}\)?-(\d{3})-(\d{4}) will do for this problem. The idea is to compile or apply the regex to the text contained in various files from the directory. I present a simple solution in Python using regex below. I have used the verbose option to explain each symbol in my regex for clarity:
My solution:
import re
def findPhoneNumbers(text):
phoneNumberPattern = re.compile(r'''
\(? # The particular regex might optionally start with a (
(\d{3}) # Followed by the area code
\)? # Followed optionally by a parenthesis
- # Followed by a hyphen
(\d{3}) # Followed by three digits
- # And a hyphe
(\d{4}) # And last 4 digits
''', re.VERBOSE)
return phoneNumberPattern.findall(text)
Test code:
text = r'''
<p><b>This is a text string. Phone number is (111)-111-1111.
</b>This is a second phone number which follows a different format of 222-222-2222.</p>
<b>But if I have a phone number which is of the format 333.333.3333, then my regex shouldn't find it.
'''
print(findPhoneNumbers(text))
Output:
[('111', '111', '1111'), ('222', '222', '2222')]
Never re-invent the wheel. You are in Darwin, and you should simply use:
- NoOne March 17, 2018[ stackoverflow.com/questions/6637882/how-can-i-use-grep-to-show-just-filenames-no-in-line-matches-on-linux/6637894 ]
And yes, you can simply use grep.
[ digitalocean.com/community/tutorials/using-grep-regular-expressions-to-search-for-text-patterns-in-linux ]
Thus, the solution is really using regex in grep with "-l" option.