193. Valid Phone Numbers
Solution
1 | grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt |
Valid Phone Numbers Explanation
Correct Regular Expressions
Pattern for (xxx) xxx-xxxx
: 1
^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$
Pattern for xxx-xxx-xxxx
: 1
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
Example Workflow
Given the input file file.txt
containing:
1
2
3
4
5987-123-4567
123 456 7890
(123) 456-7890
text 123-456-7890
(123) 456-7890 text
The command processes it as follows: 1
grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt
Expected Output
1 | 987-123-4567 |
Debugging and Attempts
Original Attempt
1 | grep -E '^\(\d{3}\) \d{3}-\d{4}$|^\d{3}-\d{3}-\d{4}$' file.txt |
Failed due to incorrect digit matching.
Corrected Solution
1 | grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt |
Uses
[0-9]
instead of\d
for better compatibility.
Debugging Script
To verify line-by-line matching: 1
2
3
4
5
6
7
8while IFS= read -r line; do
echo "Checking: '$line'"
if echo "$line" | grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$'; then
echo "Matched: $line"
else
echo "Not Matched: $line"
fi
done < file.txt
Final Thoughts
This solution ensures correct pattern matching for valid phone numbers in the specified formats, using extended regex for better readability and compatibility.