如何提取最长的匹配?

ℕʘʘ*_*ḆḽḘ 2 regex r stringr purrr

考虑这个简单的例子

library(stringr)
library(dplyr)

dataframe <- data_frame(text = c('how is the biggest ??',
                                 'really amazing stuff'))

# A tibble: 2 x 1
  text                 
  <chr>                
1 how is the biggest ??
2 really amazing stuff 
Run Code Online (Sandbox Code Playgroud)

我需要基于regex表达式提取一些术语,但仅提取最长的术语

到目前为止,我只能使用提取第一个匹配项(不需要最长的匹配项)str_extract

> dataframe %>% mutate(mymatch = str_extract(text, regex('\\w+')))
# A tibble: 2 x 2
  text                  mymatch
  <chr>                 <chr>  
1 how is the biggest ?? how    
2 really amazing stuff  really 
Run Code Online (Sandbox Code Playgroud)

我尝试一起玩,str_extract_all但是找不到有效的语法。输出应为:

# A tibble: 2 x 2
  text                  mymatch
  <chr>                 <chr>  
1 how is the biggest ?? biggest
2 really amazing stuff  amazing 
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢!

avi*_*seR 5

您可以执行以下操作:

library(stringr)
library(dplyr)

dataframe %>%
  mutate(mymatch = sapply(str_extract_all(text, '\\w+'), 
                          function(x) x[nchar(x) == max(nchar(x))][1]))
Run Code Online (Sandbox Code Playgroud)

purrr

library(purrr)

dataframe %>%
  mutate(mymatch = map_chr(str_extract_all(text, '\\w+'), 
                           ~ .[nchar(.) == max(nchar(.))][1]))
Run Code Online (Sandbox Code Playgroud)

结果:

# A tibble: 2 x 2
                   text mymatch
                  <chr>   <chr>
1 how is the biggest ?? biggest
2  really amazing stuff amazing
Run Code Online (Sandbox Code Playgroud)

注意:

如果有平局,则采取第一个。

数据:

dataframe <- data_frame(text = c('how is the biggest ??',
                                 'really amazing biggest stuff'))
Run Code Online (Sandbox Code Playgroud)