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

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

问题描述

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

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

(xxx)xxx-xxxx

xxx xxx xxxx

xxxxxxxxxx

我只能同时处理 1、2 和 4

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

说明:

([0-9]{3}) 括号内的三位数字

|

[0-9]{3} 括号内的三位数字

...使用分组括号 - (...) - 围绕替代项,因此无论哪个替代匹配项,正则表达式的其余部分都表现相同.

...with grouping parentheses - (...) - around the alternation so the rest of the regex behaves the same no matter which alternative matches.

这篇关于grep 用正则表达式表示电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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