如何改变下划线前后的单词顺序
例如
wor_hello
发布于 2021-10-30 20:35:21
我们可以这样做:
sub("(.*)_(.*)", "\\2_\\1", str1)[1] "wor_hello" "everyone_hi"发布于 2021-10-30 20:25:47
我们可以使用regex来实现这一点,即捕获单词((\\w+)),在_之前和之后,以及在替换中重新排列反向引用。
sub("^(\\w+)_(\\w+)$", "\\2_\\1", str1)
[1] "wor_hello" "everyone_hi"数据
str1 <- c("hello_wor", "hi_everyone")发布于 2021-10-30 20:59:44
使用tidyverse方法:
library(tidyverse)
words <- c("Peter_Gabriel", "Tina_Turner")
map_chr(words, ~ str_extract_all(.x, "\\w+(?=_)|(?<=_)\\w+")
%>% flatten %>% rev %>% paste0(collapse = "_"))
#> [1] "Gabriel_Peter" "Turner_Tina"https://stackoverflow.com/questions/69781882
复制相似问题