【问题标题】:R, regexpr,gregexpr, keep track of matchesR, regexpr,gregexpr, 跟踪匹配
【发布时间】:2015-03-05 14:29:36
【问题描述】:

假设我有这个 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

【问题讨论】:

    标签: regex r


    【解决方案1】:

    pattern 更改为:

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

    然后用NA 替换空字符串。不需要perl=TRUE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 2018-05-03
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多