r - 用不同的模式替换文本
问题描述
我正在处理一个包含 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)
如何改进此代码?
预期输出:
'这是我的电话号码'、'帐号是'、'她的年龄是'、'信用卡号码是'、'这是帐户列表'
解决方案
如果我们需要删除重复的 '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)
推荐阅读
- android - Android Studio 布局预览中的 Kotlin android 扩展和自定义视图
- ios - 将 SCNNode 固定在没有 ARPlaneAnchor 的位置
- android - 如何在低于 Android 9.0 的版本中使用 Biometric Prompt API
- r - 更改“likert”标准文本
- sql - 使用 SQL 查询输出进行操作
- r - 按另一个字符串中存在的字符串合并数据帧
- spring - Spring Mail 身份验证失败
- javascript - 在js中打开模态
- c++ - 错误错误:'void*' 不是指向对象的指针类型
- assembly - 在 C++ 中创建 *int - 在将函数返回值分配给全局之前,MSVC 额外存储/重新加载函数返回值的意义何在?