我有一个字符串,想将两个小写单词大写。以下实现了我想要的:
library(tidyverse)
"this is a test" %>%
str_replace_all("this", toupper("this")) %>%
str_replace_all("test", toupper("test"))
但是,我想以更有效的方式执行此操作,因为我有很多模式要替换,并且不希望每个模式单独一行。我想过用map
,但是我无法正确执行它,因为下面的代码会引发错误:"this is a test" %>%
c("this", "test") %>%
map_chr(~str_replace_all(.x, toupper(.x)))
谁能告诉我如何做到这一点?
最佳答案
在正则表达式中,您可以使用 \\U
将捕获组更改为大写。使用 |
来区分不同的图案。
val <- c("this", "test")
string <- "this is a test"
gsub(sprintf('(%s)', paste0(val, collapse = '|')), '\\U\\1', string, perl = TRUE)
#[1] "THIS is a TEST"
要回答您的问题,您可以使用
for
循环以实现您正在寻找的结果。for(i in val) {
string <- stringr::str_replace_all(string, i, toupper(i))
}
map
/lapply
没有关于中间发生的变化的“知识”,因此它适用于相同的输入。
关于r - 如何使用带有 str_replace_all 的 map 进行多个模式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68923847/