具有异常的数字掩码的正则表达式

时间:2016-07-05 06:22:55

标签: regex

我想在简历中屏蔽电话号码,其中还包含2001, 2001-03和百分比45% 87% 78.45% 56.5%中的日期。

我只想掩盖电话号码,我不需要完全屏蔽它。如果我只能掩盖难以猜测的3或4位数字,那就完成了工作。请帮助我。

Phone number formats are 
9876543210
98765 43210
98765-43210
9876 543 210
9876-543-210

3 个答案:

答案 0 :(得分:1)

以下是我的回答:

 (([0-9][- ]*){5})(([0-9][- ]*){5})

它将匹配10个数字,有或没有-或空格。

之后,您可以使用*****或任何您喜欢的内容替换第一组或第三组。

例如:

$1*****

答案 1 :(得分:1)

\d{4,5}[ -]?\d{3}[ -]?\d{2,3}

匹配的字符串:

  

9876543210, 98765 43210, 98765-43210, 9876 543 210, 9876-543-210

字符串不匹配:

45% 87% 78.45% 56.5%
2001, 2001-03

由于要求屏蔽上述格式的有效电话号码,因此我觉得不需要更复杂的正则表达式匹配无效的电话号码。

检查here

Python代码:

def fun(m):
  if m:
    return '*'*len(m.group(1))+m.group(2)

string = "Resume of candidate abcd. His phone numbers are : 9876543210, 98765 43210, 98765-43210.Date of birth of the candidate is 23-10-2013. His percentage is 57%. One more number 9876 543 213 His percentage in grad school is 44%. Another number  9876-543-210"

re.sub('(\d{4,5})([ -]?\d{3}[ -]?\d{2,3})',fun,string)

<强>输出:

'Resume of candidate abcd. His phone numbers are : *****43210, *****
43210, *****-43210. Date of birth of the candidate is 23-10-2013. His
percentage is 57%. One more number **** 543 213 His percentage in grad
school is 44%. Another number  ****-543-210'

有关re.sub的更多信息

  

re.sub(pattern, repl, string, count=0, flags=0)

     

返回通过替换最左边的非重叠获得的字符串   替换repl在字符串中出现模式。如果   找不到模式,字符串返回不变。 repl可以是一个   字符串或函数;

答案 2 :(得分:0)

只是为了帮助你...我会用python做的。 使用re模块搜索类似数字的字符串:

import re
num_re = re.compile('[0-9 -]{5,}')
with open('/my/file', 'r') as f:
    for l in f:
        for s in num_re.findall(l):
            # Do some addition testing, like 'not starting with' or any
            l.replace(s, '!!!MASKED!!!')
        print l

我并不是说这段代码已经完成,但它应该会帮助你。

顺便说一句,为什么我会使用这种方法:

  • 您可以轻松添加任何您喜欢的测试来修复误报。

  • 可读。

相关问题