【问题标题】:How do I extract the last occurring string within a parentheses with a column string into another column using stringr?如何使用 stringr 将括号内最后出现的字符串与列字符串提取到另一列中?
【发布时间】:2020-04-28 18:14:56
【问题描述】:

我在这样的列中有一组随机文本:

dplyr::tibble(text = c("I have a (brown) clock", "surrounded by (red) walls", "inside of a (blue) building with (dirty) windows",
                      "where (magical) things (unexpectedly) occur (spontaneously)"))

# A tibble: 4 x 1
  text                                                       
  <chr>                                                      
1 I have a (brown) clock                                     
2 surrounded by (red) walls                                  
3 inside of a (blue) building with (dirty) windows           
4 where (magical) things (unexpectedly) occur (spontaneously)

我想将括号中最后出现的字符串提取到另一列中,使其看起来像这样:

dplyr::tibble(text = c("I have a (brown) clock", "surrounded by (red) walls", "inside of a (blue) building with (dirty) windows",
                          "where (magical) things (unexpectedly) occur (spontaneously)"),
                  extract = c("brown", "red", "dirty", "spontaneously"))

# A tibble: 4 x 2
  text                                                        extract      
  <chr>                                                       <chr>        
1 I have a (brown) clock                                      brown        
2 surrounded by (red) walls                                   red          
3 inside of a (blue) building with (dirty) windows            dirty        
4 where (magical) things (unexpectedly) occur (spontaneously) spontaneously

【问题讨论】:

    标签: r regex dplyr stringr


    【解决方案1】:

    一个选项是stri_extract_last 来自stringi,它应该很快。在这里,我们进行正则表达式环顾以匹配左括号 ((?&lt;=\\()) 后跟一个或多个不是右括号 ([^\\)]+) 的字符

    library(dplyr)
    df1 %>%
        mutate(extract = stringi::stri_extract_last(text, regex = "(?<=\\()[^\\)]+"))
    # A tibble: 4 x 2
    #  text                                                        extract      
    #  <chr>                                                       <chr>        
    #1 I have a (brown) clock                                      brown        
    #2 surrounded by (red) walls                                   red          
    #3 inside of a (blue) building with (dirty) windows            dirty        
    #4 where (magical) things (unexpectedly) occur (spontaneously) spontaneously
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多