grep与正则表达式的电话号码 [英] grep with regex for phone number
问题描述
我想从文件中获取电话号码。我知道数字有不同的形式,我可以处理一个,但不知道如何获得统一的正则表达式。例如
-
xxx-xxx-xxxx
-
(xxx)xxx-xxxx
-
xxx xxx xxxx
-
xxxxxxxxxx
我只能一起处理1,2和4
grep'[0-9] \ {3 \} [ - ] \?[0-9] \ {3 \} [ - ] \?[0 -9] \ {4 \}'文件
是否有任何一个正则表达式可以处理所有
\ {3 \})\ | [0-9] \ {3 \} \)[ - ] \?[0-9] \ {3 \} [ - ] \? [0-9] \ {4 \}'文件说明:
([0-9] \ {3 \})
括号内的三位数字
\ |
或
[0-9] \\ \\ {3 \}
三位数字不是里面的元素
...带有分组圆括号 - \(... \)
- 围绕交替,所以正则表达式的其余部分表现相同,无论哪种方法匹配。
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.
这篇关于grep与正则表达式的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!