在 R 中查找 table 时精确匹配字符串
match strings exactly on lookup table in R
我有一个 table 的查找值,其中包含要查找和替换的模式,但这些模式的字符串包含彼此,我想完全匹配它们。
lookup <- tibble(
pattern = c("ONE", "ONET", "ONETR"),
replacement = c("one new", "this is 2", "for 3")
)
other_table <- tibble(
strings = c(
"I want to replace ONE",
"Or ONET is what to change",
"We can change ONE again",
"ONETR also can be replaced"
),
other_dat = 1:4
)
我试过使用 stringi
但是当模式相互包含时这不起作用。
other_table %>%
mutate(
strings = stringi::stri_replace_all_fixed(
strings,
pattern = lookup$pattern,
replacement = lookup$replacement,
vectorize_all = FALSE)
)
我可以使用什么函数将 in_table$strings
中找到的所有模式替换为 lookup$replacement
?
期望的输出:
strings other_dat
<chr> <int>
1 I want to replace one new 1
2 Or this is 2 is what to change 2
3 We can change one new again 3
4 for 3 also can be replaced 4
感谢任何帮助!
在正则表达式中使用单词边界(不固定),例如 "\b"
。
other_table %>%
mutate(
strings = stringi::stri_replace_all(
strings,
regex = paste0("\b", lookup$pattern, "\b"),
replacement = lookup$replacement,
vectorize_all = FALSE)
)
# # A tibble: 4 x 2
# strings other_dat
# <chr> <int>
# 1 I want to replace one new 1
# 2 Or this is 2 is what to change 2
# 3 We can change one new again 3
# 4 for 3 also can be replaced 4
我有一个 table 的查找值,其中包含要查找和替换的模式,但这些模式的字符串包含彼此,我想完全匹配它们。
lookup <- tibble(
pattern = c("ONE", "ONET", "ONETR"),
replacement = c("one new", "this is 2", "for 3")
)
other_table <- tibble(
strings = c(
"I want to replace ONE",
"Or ONET is what to change",
"We can change ONE again",
"ONETR also can be replaced"
),
other_dat = 1:4
)
我试过使用 stringi
但是当模式相互包含时这不起作用。
other_table %>%
mutate(
strings = stringi::stri_replace_all_fixed(
strings,
pattern = lookup$pattern,
replacement = lookup$replacement,
vectorize_all = FALSE)
)
我可以使用什么函数将 in_table$strings
中找到的所有模式替换为 lookup$replacement
?
期望的输出:
strings other_dat
<chr> <int>
1 I want to replace one new 1
2 Or this is 2 is what to change 2
3 We can change one new again 3
4 for 3 also can be replaced 4
感谢任何帮助!
在正则表达式中使用单词边界(不固定),例如 "\b"
。
other_table %>%
mutate(
strings = stringi::stri_replace_all(
strings,
regex = paste0("\b", lookup$pattern, "\b"),
replacement = lookup$replacement,
vectorize_all = FALSE)
)
# # A tibble: 4 x 2
# strings other_dat
# <chr> <int>
# 1 I want to replace one new 1
# 2 Or this is 2 is what to change 2
# 3 We can change one new again 3
# 4 for 3 also can be replaced 4