如何查找字符串中的某个部分并仅保留该部分

Kas*_*eek 6 r

找到例如字符串":[1-9]*"并且仅保留该部分的最简洁方法是什么?

您可以使用regexec来获取起点,但是不是有更简洁的方法来立即获得值吗?

例如:

test <- c("surface area: 458", "bedrooms: 1", "whatever")
regexec(": [1-9]*", test)
Run Code Online (Sandbox Code Playgroud)

我如何立即获得

c(": 458",": 1", NA )
Run Code Online (Sandbox Code Playgroud)

hwn*_*wnd 8

您可以使用基本R来处理这个问题.

> x <- c('surface area: 458', 'bedrooms: 1', 'whatever')
> r <- regmatches(x, gregexpr(':.*', x))
> unlist({r[sapply(r, length)==0] <- NA; r})
# [1] ": 458" ": 1"   NA  
Run Code Online (Sandbox Code Playgroud)

虽然,我发现它更简单...

> x <- c('surface area: 458', 'bedrooms: 1', 'whatever')
> sapply(strsplit(x, '\\b(?=:)', perl=T), '[', 2)
# [1] ": 458" ": 1"   NA 
Run Code Online (Sandbox Code Playgroud)


akr*_*run 7

library(stringr)
str_extract(test, ":.*")
#[1] ": 458" ": 1"   NA     
Run Code Online (Sandbox Code Playgroud)

或者更快的方法 stringi

library(stringi)
stri_extract_first_regex(test, ":.*")
#[1] ": 458" ": 1"   NA     
Run Code Online (Sandbox Code Playgroud)

如果您需要保留没有匹配项的值

gsub(".*(:.*)", "\\1", test)
#[1] ": 458"    ": 1"      "whatever"
Run Code Online (Sandbox Code Playgroud)