thiagowfx's avatar

¬ just serendipity 🍀 (not just serendipity)

LeetCode #193: Valid Phone Numbers

• 70 words • 1 min • updated

LeetCode #193: Valid Phone Numbers:

shell
# Read from the file file.txt and output all valid phone numbers to stdout.
grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt

egrep is the easiest way to go. It is a bit hard to remember its syntax.

A bit more optimized, grouping alternations at the beginning:

shell
# Read from the file file.txt and output all valid phone numbers to stdout.
grep -E '^(\([0-9]{3}\) [0-9]{3}|[0-9]{3}-[0-9]{3})-[0-9]{4}$' file.txt