grep与正则表达式的电话号码 [英] grep with regex for phone number

查看:268
本文介绍了grep与正则表达式的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中获取电话号码。我知道数字有不同的形式,我可以处理一个,但不知道如何获得统一的正则表达式。例如


  1. xxx-xxx-xxxx


  2. (xxx)xxx-xxxx


  3. xxx xxx xxxx


  4. 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

  1. xxx-xxx-xxxx

  2. (xxx)xxx-xxxx

  3. xxx xxx xxxx

  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆