在R中使用stringr在最后一个子字符串之后找到剩余的字符串

Jam*_*s N 4 regex r stringr

如何使用str_match提取最后一个子字符串之后的剩余字符串。

例如,对于字符串“带奶油的苹果,橙子和香蕉”,我想在最后一次出现“和”之后提取该字符串的其余部分,以返回“香蕉和奶油”。

我尝试了此命令的许多替代方法,但它要么一直返回第一个“和”之后的字符串其余部分,要么返回空字符串。

library(stringr)

str_match("apples and oranges and bananas with cream", "(?<= and ).*(?! and )")

    #     [,1]                             
    #[1,] "oranges and bananas with cream"
Run Code Online (Sandbox Code Playgroud)

我已经在StackOverflow上搜索了解决方案,并找到了一些针对javascript,Python和base R的解决方案,但没有找到针对stringer包的解决方案。

谢谢。

42-*_*42- 5

(不过,不知道str_match。BaseR正则表达式就足够了。)由于正则表达式模式匹配是“贪婪的”,即它将搜索所有匹配项并选择最后一个匹配项,这就是:

sub("^.+and ", "", "apples and oranges and bananas with cream")
#[1] "bananas with cream"
Run Code Online (Sandbox Code Playgroud)

我很确定在hadleyverse的“润滑”角上会有一个等效项。

然后失败:

 library(lubridate)

Attaching package: ‘lubridate’

The following object is masked from ‘package:plyr’:

    here

The following objects are masked from ‘package:data.table’:

    hour, isoweek, mday, minute, month, quarter, second, wday, week, yday, year

The following object is masked from ‘package:base’:

    date

> str_replace("apples and oranges and bananas with cream", "^.+and ", "")
Error in str_replace("apples and oranges and bananas with cream", "^.+and ",  : 
  could not find function "str_replace"
Run Code Online (Sandbox Code Playgroud)

因此它不在其中,pkg:lubridate而在stringr其中(据我所知,它是stringi程序包的一个非常轻巧的包装器):

library(stringr)
 str_replace("apples and oranges and bananas with cream", "^.+and ", "")
[1] "bananas with cream"
Run Code Online (Sandbox Code Playgroud)

我确实希望那些对非基本软件包功能提出疑问的人会library打来电话,让受访者了解他们的工作环境。