如何从给定 character/text 的两侧同时删除 text/character (#regex)?

how to remove at once text/character from both sides of a given character/text (#regex)?

删除 r 中给定 character/text 左右两侧的文本的最简单方法是什么?

我有以下数据集的示例: a = c("C:\final docs with data/Gakenke_New_Sanitation.xlsx", "C:\final docs with data/Gatsibo_New_Sanitation.xlsx", "C:\final docs with data/Rutsiro_New_Sanitation.xlsx")

我的预期输出将保留:Gakenke、GatsiboRutsiro

我知道,我可以分解这个任务并使用 mutate() 处理它,如下所示:

a %>% mutate(a = str_remove(a, "C.+/"), a = str_remove(a,"_.+")).

我现在的问题是,我可以将哪个简单 pattern 传递给该变异函数以保持我的预期结果:Gakenke、GatsiboRutsiro .

非常感谢任何帮助。谢谢!

可能的解决方案,基于 stringr::str_extract 和环顾四周:

library(tidyverse)

a %>% 
  str_extract("(?<=data\/).*(?=\_New)")

#> [1] "Gakenke" "Gatsibo" "Rutsiro"

您可以使用

a = c("C:\final docs with data/Gakenke_New_Sanitation.xlsx", "C:\final docs with data/Gatsibo_New_Sanitation.xlsx",  "C:\final docs with data/Rutsiro_New_Sanitation.xlsx")
library(stringr)
str_remove_all(a, "^.*/|_.*")
## => [1] "Gakenke" "Gatsibo" "Rutsiro"

stringr::str_remove_all 删除找到的所有模式。 ^.*/|_.* 匹配从开始到最后一个 / 的字符串,然后从 _ 到字符串的结尾(注意字符串假定没有换行符)。