您可以尝试这种基本的 R 方法。我们将提取电话号码,用 11 个随机数字对其进行屏蔽,然后将它们放回原来的位置。请注意,此方法不会更改 "Year(2007,2019,2020)" 中的任何数字,如果此行为是您想要的。
rand_mask <- function(x) {
m1 <- regexpr("\\b\\d{3}([-.]?)\\d{4}\\1\\d{4}\\b", x)
phones <- regmatches(x, m1)
m2 <- gregexpr("\\d", phones)
rand <- replicate(length(m2), sample.int(10L, 11L, replace = TRUE) - 1L, simplify = FALSE)
regmatches(phones, m2) <- rand
regmatches(x, m1) <- phones
x
}
测试
> set.seed(1234L)
> rand_mask(x)
[1] "954-8453-1659" "John 537-3347-3723" "Phone: 941-7326-8253" "Peter 791.4505.7250" "Year(2007,2019,2020)"
[6] "Alice 08790795282"
> rand_mask(x)
[1] "589-6578-2214" "John 796-5386-2547" "Phone: 036-2830-5595" "Peter 440.1591.4329" "Year(2007,2019,2020)"
[6] "Alice 34955828570"
> rand_mask(x)
[1] "815-7526-4562" "John 268-7295-6144" "Phone: 827-2728-3732" "Peter 960.8214.9580" "Year(2007,2019,2020)"
[6] "Alice 28834025451"
更新
这个用随机数替换所有数字。
rand_mask2 <- function(x) {
m <- gregexpr("\\d", x)
regmatches(x, m) <- lapply(lengths(m), \(n) sample.int(10L, n, replace = TRUE) - 1L)
x
}
测试
> set.seed(1234L)
> rand_mask2(x)
[1] "954-8453-1659" "John 537-3347-3723" "Phone: 941-7326-8253" "Peter 791.4505.7250" "Year(0879,0795,2825)"
[6] "Alice 89657822147"
> rand_mask2(x)
[1] "965-3862-5470" "John 362-8305-5954" "Phone: 401-5914-3293" "Peter 495.5828.5708" "Year(1575,2645,6226)"
[6] "Alice 87295614482"
> rand_mask2(x)
[1] "727-2837-3296" "John 082-1495-8028" "Phone: 834-0254-5121" "Peter 656.7306.9729" "Year(1707,7594,3930)"
[6] "Alice 55233202082"