【问题标题】:Extract a string between two words, with multiple patterns提取两个单词之间的字符串,具有多种模式
【发布时间】:2022-01-22 02:34:58
【问题描述】:

我有一系列字符串,例如“任命 XX 为负责人”、“任命 YY 为负责人”(包含在标有“标题”的列中标有“df”的数据框中)

我想提取两个不同表达式之间的名称 XX、XY。

我目前正在使用以下内容:

df$name <- df$title %>% 
  str_extract(regex(pattern = "(?<=Appointment of).*(?= as)", ignore_case=TRUE))

但是,这仅适用于两种可能的模式之一。

df$name <- df$title %>% 
  str_extract(regex(pattern = "(?<=Appointment of).*(?= as)"|"(?<=joins).*(?= as)", ignore_case=TRUE))

这当然行不通。 如何创建多个模式以输入 str_extract?

如果需要,很乐意提供更多详细信息!

非常感谢

【问题讨论】:

  • "(?&lt;=Appointment of).*?(?= as)|(?&lt;=joins).*?(?= as)"?还是"(?&lt;=Appointment of|joins).*?(?= as)"
  • 嗨,Wiktor,这太棒了,我早该想到了!它有效!
  • 我建议用测试数据和预期结果更新问题。
  • 嗨,Wiktor,它可以工作...我在尝试代码时只是有太多空白空间,但现在它可以工作了!

标签: r regex stringr


【解决方案1】:

strapply 可以在不使用零宽度结构的情况下做到这一点。仅返回第二个捕获组。

library(gsubfn)

x <- c("the appointment of XX as head", "appoints YY as head") # input
strapply(x, "(appointment of|appoints) (.*?) as head", ~ ..2, simplify = TRUE)
## [1] "XX" "YY"

或使用 (?:...) 指定第一个带括号的部分不是捕获组:

strapply(x, "(?:appointment of|appoints) (.*?) as head", simplify = TRUE)
## [1] "XX" "YY"

基础 R

在基础 R 中,如果 x 的每个组件都匹配,则可以使用 sub 完成

sub(".*(appointment of|appoints) (.*?) as head.*", "\\2", x)
## [1] "XX" "YY"

如果不是,则为 strcapture

proto <- data.frame(dummy = character(0), value = character(0))
strcapture("(appointment of|appoints) (.*?) as head", x, proto)[, 2]
## [1] "XX" "YY"

【讨论】:

    【解决方案2】:

    你可以使用

    df$name <- df$title %>% 
      str_extract(regex(pattern = "(?<=\\bAppointment of\\s|\\bjoins\\s).*?(?=\\s+as\\b)", ignore_case=TRUE))
    

    详情

    • (?&lt;= - 积极回顾的开始
      • \bAppointment of\s - 一个单词边界 (\b)、Appointment of,然后是一个空格字符 (\s)
    • | - 或
      • \bjoins\s - 一个完整的单词 joins 和一个空格
    • ) - 回顾结束
    • .*? - 除换行符以外的任何零个或多个字符
    • (?=\s+as\b) - 需要一个或多个空格、as 和紧邻当前位置右侧的单词边界的正向前瞻。

    注意stringr中的lookbehind模式并不是严格固定宽度的,你可以使用

    "(?<=\\bAppointment of\\s{1,100}|\\bjoins\\s{1,100}).*?(?=\\s+as\\b)"
    

    \s{1,100} 可以匹配一到一百个空格字符。

    【讨论】:

    • 非常感谢 - 不仅它有效,而且我更好地理解了正则表达式语法!非常感谢
    猜你喜欢
    • 2012-04-13
    • 2013-12-12
    • 2014-05-28
    • 2013-05-28
    • 2017-04-04
    • 2018-11-23
    • 1970-01-01
    • 2015-04-08
    • 2011-11-30
    相关资源
    最近更新 更多