【问题标题】:replace text with different pattern用不同的模式替换文本
【发布时间】:2020-08-02 06:55:19
【问题描述】:

我正在处理一个包含 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)

如何改进此代码?

预期输出:

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

【问题讨论】:

    标签: r regex


    【解决方案1】:
    trimws(gsub("x{2,}", "", x, ignore.case = T))
    

    trimws(gsub("(x|X){2,}", "", x))
    
    [1] "This is my phone number"      "The account number is"        "Her age is"                  
    [4] "The credit number is"         "This is the list of accounts"
    

    【讨论】:

    • @capiono 感谢您的接受。但是,老实说,我的解决方案不值得。在我看来,您应该接受@akrun 的解决方案。他的答案不仅在我之前,而且更安全,因为它确保您所说的掩码必须以空格为界的字符串出现(参见\\b)。我的解决方案还匹配并因此删除了出现在 inside 单词中的字符串,例如 xx。当然,这种情况在英语中是极不可能的(我只想到了品牌名称Exxon)。但总而言之,@akrun 的解决方案更智能。
    • @akrun 感谢您回答这个问题,这两种解决方案都非常有效。对不起,我没有选择你的。老实说,我只是接受了顶部的答案。再次感谢。
    【解决方案2】:

    如果我们需要删除重复的 'x' 或 ('X'),请指定单词边界 (\\b) 后跟一个或多个 'x' (\\x+) 直到单词边界 (@ 987654323@) 并将其替换为空白 ("")。另外,也可以使用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)
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      相关资源
      最近更新 更多