【问题标题】:Extract 2 terms before specific character在特定字符之前提取 2 个术语
【发布时间】:2016-10-16 02:38:45
【问题描述】:

我想提取 Twitter @handle 前面的两个词

x <- c("this is a @handle", "My name is @handle", "this string has @more than one @handle")

执行以下操作仅提取 last @handle 之前的所有文本,所有@handle 我都需要它

(ext <- stringr::str_extract_all(x, "^.*@"))
[[1]]
[1] "this is a @"

[[2]]
[1] "My name is @"

[[3]]
[1] "this string has @more than one @"

【问题讨论】:

  • 你可能想要str_split

标签: r stringr stringi


【解决方案1】:

您可以使用量词{2} 指定要在字符@ 之前提取多少个单词。一个单词由单词字符\\w+ 和一个单词边界组成,在您的情况下是空格。我们可以使用trimws 函数来删除不必要的前导和尾随空格:

library(stringr)
lapply(str_extract_all(x, "(\\w+\\s+){2}(?=@)"), trimws)

#[[1]]
#[1] "is a"

#[[2]]
#[1] "name is"

#[[3]]
#[1] "string has" "than one"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    相关资源
    最近更新 更多