Mohaa Mohaa - 11 months ago 65
R Question

How to extract substrings that start and end with a specific character, in a single string?

For example I have the following string:

sample = "I am a good guy; he is cool; I am a cool dude; let's do it!"

I need to find substrings which start with "I am" and end with ";" so the output should be like:

I am a good guy
I am a cool dude

Any suggestions how to do this in R? Thanks


Here is a stringr library solution:

str_match_all(sample, "I am.*?;")
#     [,1]               
#[1,] "I am a good guy;" 
#[2,] "I am a cool dude;"

stringer has several very powerful functions for dealing with splitting and extracting information from strings.