从 R 中的文本字符串中提取 N 个匹配项?

Extracting N number of matches from a text string in R?

我在 R 中使用 stringr,我有一个文本字符串,其中列出了新闻文章的标题。我想提取这些标题,但只提取出现的前 N-number 个标题。在我的示例文本字符串中,我有三个文章标题,但我只想提取前两个。

如何告诉 str_extract 只收集前 2 个标题?谢谢。

这是我当前的代码和示例文本。

library(stringr)

这是示例文本。

texting <- ("Time: Friday, September 14, 2018 4:34:00 PM EDT\r\nJob Number: 73591483\r\nDocuments (100)\r\n 1. U.S. Stocks Rebound Slightly After Tech-Driven Slump\r\n   Client/Matter: -None-\r\n   Search Terms: trade war or US-China trade or china tariff and not dealbook\r\n   Search Type: Terms and Connectors\r\n   Narrowed by:\r\n             Content Type                         Narrowed by\r\n             News                                 Sources: The New York Times; Content Type: News;\r\n                                                  Timeline: Jan 01, 2018 to Dec 31, 2018\r\n 2. Shifting Strategy on Tariffs\r\n   Client/Matter: -None-\r\n   Search Terms: trade war or US-China trade or china tariff and not dealbook\r\n 100. Example")
titles.1 <- str_extract_all(texting, "\d+\.\s.+")
titles.1

当前代码返回字符串中的所有三个匹配项:

[[1]]

[1] "1. U.S. Stocks Rebound Slightly After Tech-Driven Slump"

[2] "2. Shifting Strategy on Tariffs"                        

[3] "100. Example"

我只希望它收集前两个匹配项。

您可以使用选项 simplify = TRUE 来获取矢量作为结果,而不是列表。然后,从 vector

中选取前 N 个元素
titles.1 <- str_extract_all(texting, "\d+\.\s.+", simplify = TRUE)[1:2]