193. Valid Phone Numbers
Solution
1grep -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:
1987-123-4567
2123 456 7890
3(123) 456-7890
4text 123-456-7890
5(123) 456-7890 text
The command processes it as follows:
1grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$' file.txt
Expected Output
1987-123-4567
2(123) 456-7890
Debugging and Attempts
Original Attempt
1grep -E '^\(\d{3}\) \d{3}-\d{4}$|^\d{3}-\d{3}-\d{4}$' file.txt
Failed due to incorrect digit matching.
Corrected Solution
1grep -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\dfor better compatibility.
Debugging Script
To verify line-by-line matching:
1while IFS= read -r line; do
2 echo "Checking: '$line'"
3 if echo "$line" | grep -E '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}-[0-9]{3}-[0-9]{4}$'; then
4 echo "Matched: $line"
5 else
6 echo "Not Matched: $line"
7 fi
8done < 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.