繁体   English   中英

R,regexpr,gregexpr,跟踪比赛

[英]R, regexpr,gregexpr, keep track of matches

假设我有此data.frame,并希望将A列与以下模式匹配。 这可以使用regexpr或gregexpr来完成。 但是我想跟踪匹配的行以及匹配本身。

df <- data.frame(A=c("where is the pencil? ","the white cat in the kitchen","green hat is over the blue ocean"))

> df
##                                  A
## 1            where is the pencil? 
## 2     the white cat in the kitchen
## 3 green hat is over the blue ocean

pattern <- ("(blue|white|green) \\w*")

regmatches(df[,1],regexpr(pattern,df[,1],perl=TRUE))

> regmatches(df[,1],regexpr(pattern,df[,1],perl=TRUE))
## [1] "white cat" "green hat"

所需的输出:

##                                  A     match
## 1            where is the pencil?       <NA>
## 2     the white cat in the kitchen white cat
## 3 green hat is over the blue ocean green hat

pattern更改为:

pattern <- paste0(pattern, "|$")

然后将空字符串替换为NA 不需要perl=TRUE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM