Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

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

$
0
0

I am using stringr in R, and I have a string of text that lists titles of news articles. I want to extract these titles, but only the first N-number of titles that appear. In my example string of text, I have three article titles, but I only want to extract the first two.

How can I tell str_extract to only collect the first 2 titles? Thank you.

Here is my current code with the example texts.

library(stringr)

Here is the example text.

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

The current code brings back all three matches in the string:

[[1]]

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

[2] "2. Shifting Strategy on Tariffs"

[3] "100. Example"

I only want it to collect the first two matches.


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>