首页 > 解决方案 > 用不同的模式替换文本

问题描述

我正在处理一个包含 PII 信息的文本列表,这些信息被屏蔽为 XXXX XXXX,这可以是电话号码或地址号码。我想取下面具。

x <- c('This is my phone number xxx xxx xxx', 'The account number is XXXXXXXXXX', 'Her age is xx', 'The credit number is xxxx xxxx xxxx xxxx', 'This is the list of accounts xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx')

我写了这样的东西,但它并没有取代一切:

gsub("(?:\\s+|^)\\S*(?<!\\w)(?:xxxx?|xxxxxxxx)(?!\\w)\\S*", "", x, perl=TRUE)

如何改进此代码?

预期输出:

'这是我的电话号码'、'帐号是'、'她的年龄是'、'信用卡号码是'、'这是帐户列表'

标签: rregex

解决方案


如果我们需要删除重复的 'x' 或 ('X'),请使用单词边界 ( \\b) 后跟一个或多个 'x' ( \\x+) 直到单词边界 ( \\b) 指定模式,并将其替换为空白 ( "")。另外,也可以使用ignore.case = TRUE(默认情况下FALSE)来匹配大写

trimws(gsub("\\bx+\\b", "", x, ignore.case = TRUE))
#[1] "This is my phone number"   
#[2] "The account number is"     
#[3] "Her age is"       
#[4] "The credit number is"        
#[5] "This is the list of accounts"

如果我们在单词边界之前使用零个或多个空格,则trimws可以删除

gsub("\\s*\\bx+\\b\\s*", "", x, ignore.case = TRUE)

推荐阅读