I would like to get the phone numbers from a file. I know the numbers have different forms, I can handle for a single one, but don't know how to get a uniform regex. For example
xxx-xxx-xxxx
(xxx)xxx-xxxx
xxx xxx xxxx
xxxxxxxxxx
I can only handle 1, 2, and 4 together
grep '[0-9]\{3\}[ -]\?[0-9]\{3\}[ -]\?[0-9]\{4\}' file
Is there any one single regex can handle all of these four forms?
grep '\(([0-9]\{3\})\|[0-9]\{3\}\)[ -]\?[0-9]\{3\}[ -]\?[0-9]\{4\}' file
Explanation:
([0-9]\{3\})
three digits inside parentheses
\|
or
[0-9]\{3\}
three digits not inside parens
...with grouping parentheses - \(...\)
- around the alternation so the rest of the regex behaves the same no matter which alternative matches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With