我有一个向量,其中每个元素都是一个字符串。我只想将字符串的一部分保留在 '==' 之前,无论它是在字符串的开头、& 符号之后,还是在 | 之后。象征。这是我的数据:
data <- c("name=='John'", "name=='David'&age=='50'|job=='Doctor'&city=='Liverpool'",
"job=='engineer'&name=='Andrew'",
"city=='Manchester'", "age=='40'&city=='London'"
)
我的理想格式是这样的:
[1] "name"
[2] "name" "age" "job" "city"
[3] "job" "name"
[4] "city"
[5] "age" "city"
我得到的最接近的是使用 qdap 库中的 genXtract,它以上面的格式放置数据,但我只知道如何在一个条件下使用它,即
qdap::genXtract(data, "&", "==")
但我不仅想要 & 和 == 之间的字符串部分,还想要 | 之间的部分and == 或字符串的开头 and ==
答案 0 :(得分:2)
这个正则表达式的作用是在 ==
出现之前捕获所有 a-zA-Z0-9(=字母和数字)。
stringr::str_extract_all( data, "[0-9a-zA-Z]+(?=(==))")
[[1]]
[1] "name"
[[2]]
[1] "name" "age" "job" "city"
[[3]]
[1] "job" "name"
[[4]]
[1] "city"
[[5]]
[1] "age" "city"
如果您希望输出为向量,请使用
L <- stringr::str_extract_all( data, "[0-9a-zA-Z]+(?=(==))" )
unlist( lapply( L, paste, collapse = " " ) )
结果
[1] "name"
[2] "name age job city"
[3] "job name"
[4] "city"
[5] "age city"
答案 1 :(得分:0)
在base R
中,这可以通过regmatches/gregexpr
lst1 <- regmatches(data, gregexpr("\\w+(?=\\={2})", data, perl = TRUE))
sapply(lst1, paste, collapse = " ")
#[1] "name"
#[2] "name age job city"
#[3] "job name"
#[4] "city"
#[5] "age city"