r - 如何使用带有 str_replace_all 的 map 进行多个模式替换

标签 r regex string

我有一个字符串,想将两个小写单词大写。以下实现了我想要的:

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/

相关文章:

regex - 我接受空字符串和公寓号的简单正则表达式有什么问题?

regex - 如何使用正则表达式路径设置 Kubernetes Ingress 规则?

java - 如何在没有资源图像的情况下显示图像

java - Protobuf 生成器 : set string field without memory allocation

R正则表达式匹配已知字符以外的东西

r - 如果列采用特定值,则分配新变量

r - stringi R 忽略重音特殊字符来匹配

javascript - 正则表达式模式抛出词法分析器错误 AngularJS

java - 在android中将CharSequence的首字母更改为大写

c++ - Rcpp第一次编译遇到问题