我有以下 100 個字串:
[3] "Department_Complementary_Demand_Converted_Sum"
[4] "Department_Home_Demand_Converted_Sum"
[5] "Department_Store A_Demand_Converted_Sum"
[6] "Department_Store B_Demand_Converted_Sum"
...
[100] "Department_Unisex_Demand_Converted_Sum"
顯然,我可以為每個字串使用substr()不同的字串索引開始和結束值。但正如人們所看到的,所有的字串都Department_以_Demand_Converted_Sum. 我只想提取介于兩者之間的內容。如果有一種方法可以始終從左側的索引 11 開始并從左側的索引 21 結束,那么我可以在上面的所有 100 個字串上運行 for 回圈。
例子
給定輸入: Department_Unisex_Demand_Converted_Sum
預期輸出: Unisex
uj5u.com熱心網友回復:
看起來像環視的經典案例:
library(stringr)
str_extract(str, "(?<=Department_)[^_] (?=_)")
[1] "Complementary" "Home" "Store A"
資料:
str <- c("Department_Complementary_Demand_Converted_Sum",
"Department_Home_Demand_Converted_Sum",
"Department_Store A_Demand_Converted_Sum")
uj5u.com熱心網友回復:
使用strsplit(),
sapply(strsplit(string, '_'), '[', 2)
# [1] "Complementary" "Home" "Store A"
或stringi::stri_sub_all()。
unlist(stringi::stri_sub_all(str, 12, -22))
# [1] "Complementary" "Home" "Store A"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370906.html
上一篇:多個句子的首字母大寫,其他小寫
