我知道如何在 Python 中实现,但无法在 R 中实现
> string <- "this is a sentence"
> pattern <- "\b([\w]+)[\s]+([\w]+)[\W]*?$"
Error: '\w' is an unrecognized escape in character string starting "\b([\w"
> match <- regexec(pattern, string)
> words <- regmatches(string, match)
> words
[[1]]
character(0)
最佳答案
sub('.*?(\\w+)\\W+\\w+\\W*?$', '\\1', string)
#[1] "a"
上面写着 - 不贪婪地寻找任何东西,直到你到达序列 - 一些单词字符 + 一些非单词字符 + 一些单词字符 + 可选的非单词字符 + 字符串结尾,然后提取该序列中的第一个单词字符集合
关于regex - 提取字符串中倒数第二个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18363688/