2017-03-29 77 views
1

部分匹配我可以用向量str我輸入ex配合下面的代碼grep的作爲R

這裏「EXP」與str

str <- c("Regular", "expression", "examples of R language")  
x <- grep("exp",str,value=F) 

匹配,而是我想與str匹配「表情」像這樣

輸入是「表達式」,它應該與下例中的str「exp」匹配

str <- c("Regular", "exp", "examples of R language")` 
x <- grep("expression",str,value=F) 
x 

#exp 

我的x =「表達式」應該與str「exp」匹配,結果應該給「exp」

有沒有辦法實現這個?

回答

1

我們需要提取子字符串。在base R,這可以用regexpr/regmatches

regmatches(str, regexpr("exp", str)) 
#[1] "exp" 

或者使用stringr/stringi

library(stringr) 
na.omit(str_extract(str, 'exp')) 
#[1] "exp" 

使用grep我們可以發現是否有疑問語氣匹配或不能這樣做。它返回元素的數字索引或邏輯向量(使用grepl)。與value = TRUE,它返回匹配的元素,而不是部分子字符串

+0

感謝您花時間回覆,但您的答案不滿足我的要求。我知道如何匹配「exp」和「expression」,並且我已經用代碼編寫了它。我想匹配「表達」到「exp」。請仔細閱讀說明。再次感謝。 –

+0

@SubharanjanSahoo那麼,你的描述很混亂bcz你使用'「exp」某處,然後「表達」 – akrun

+0

@SubharanjanSahoo在這種情況下,嘗試'substr(regmatches(str,regexpr(「expression」,str)),1,3 )# [1]「exp」或者可能是'grep(substr(「expression」,1,3),str,value = TRUE) [1]「exp」' – akrun